我正在 AWS 实例上部署我的应用程序。我有前端和后端作为 docker 镜像。
我想使用 Nginx。当我运行此配置并转到给定公共 URL 的 AWS 时,nginx 返回 502。
/api
/文档
他们正在工作,但是
/行政
/
返回502。
这是我的conf文件:
docker-compose.yml:
backend:
container_name: backend
image: ${BACKEND_IMAGE_NAME}:${IMAGE_TAG}
command: python manage.py runserver 0.0.0.0:8000
env_file:
- .env
expose:
- 8000
frontend:
container_name: frontend
image: ${FRONTEND_IMAGE_NAME}:${IMAGE_TAG}
expose:
- 3002
env_file:
- .env
nginx:
build: ./nginx
ports:
- 80:80
depends_on:
- backend
- frontend
这是 nginx 配置:
upstream backend {
server backend:8000;
}
upstream frontend {
server frontend:3002;
}
server {
listen 80;
location /api/ {
proxy_pass http://backend;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /docs/ {
proxy_pass http://backend;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location /admin/ {
proxy_pass http://backend;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
}
location / {
proxy_pass http://frontend; # Proxy to frontend on port 3002
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_redirect off;
# Ensure that Nginx handles large files and requests well
client_max_body_size 100M;
# Timeout settings to prevent 502 Bad Gateway
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}```
nginx docker 文件:
FROM nginx:1.27
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d```
前端docker文件:
# Use a Node.js base image
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install
# Copy the rest of the application code
COPY . .
# Build the app for production
RUN npm run build
# Expose the port your app runs on
EXPOSE 3002
# Start the app
CMD ["npm", "run", "start"]
后端docker文件:
FROM python:3.12
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /app/src
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app/
EXPOSE 8000
经过几个小时的努力,nginx 的配置是正确的,但由于我没有将文件挂载为卷,所以我需要使用 conf 文件重建 nginx 映像。当容器重新启动时,conf 文件不会自动同步。我重建并修复了。