当尝试在浏览器中访问 localhost 时,我收到 502 bad gateway 在 docker 容器中记录以下错误:
failed (111: Connection refused) while connecting to upstream, client: 172.26.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://172.26.0.5:3000/", host: "localhost"
下面是nginx.conf文件:
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
sendfile on;
keepalive_timeout 65;
upstream frontend {
server frontend:3000;
}
upstream api {
server api:8000;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://frontend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /api {
proxy_pass http://api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
这是 docker-compose.yml:
version: '3'
services:
nginx:
image: nginx
ports:
- "80:80"
volumes:
- ./backend/nginx.conf:/etc/nginx/nginx.conf # Mount the Nginx config file
depends_on:
- api
- frontend
api:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- '${APP_PORT:-8000}:80'
volumes:
- '.:/var/www/'
depends_on:
- mysql
frontend:
tty: true
build:
context: ./frontend
dockerfile: Dockerfile
container_name: frontend
ports:
- "3000:3000"
volumes:
- ./frontend:/app
depends_on:
- api
stdin_open: true
mysql:
image: 'mysql:8.0'
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
MYSQL_DATABASE: '${DB_DATABASE}'
MYSQL_PASSWORD: '${DB_PASSWORD}'
volumes:
- 'mysql_data:/var/lib/mysql'
mailhog:
image: 'mailhog/mailhog:latest'
ports:
- "1025:1025"
- "8025:8025"
volumes:
mysql_data:
driver: local
调试步骤:
此时 Nginx 似乎已正确配置,并且能够通过 ping 与上游通信,但在需要路由请求时无法与前端正确建立连接。
也许问题根源在于 CORS 的某些 nuxt/vue 配置?
也许现在解决你的问题已经太晚了,但是 nuxt 必须正确配置才能接受来自外部网络的连接。否则,它会拒绝所有不是来自主机的连接。 您可以在 docker 环境或 nuxt 配置中设置“HOST”变量:
在 docker-compose.yaml 中:
environment:
HOST: 0
PORT: 3000
或者在 nuxt.config.js 中:
server: {
port: 3000,
host: '0.0.0.0' // do not put localhost (only accessible from the host machine)
}
这个问题的答案对我有帮助: 无法使用 Docker 将基于 nuxt 的 Express 服务器转发到主机