我一直在努力将我们的生产环境 docker 化,它由一个 React 前端组成,该前端会向 Nginx 服务器发出 API 调用。Nginx 服务器将所有请求反向代理到 ASP .NET Core 应用程序。我已设法使后端映像(.NET 和数据库)通过 docker-compose 正常工作和通信,但现在我试图绑定 Nginx,但它无法正常工作。我的配置如下:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events { worker_connections 1024; }
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
# docker provides 'app' network address for api image
upstream app_servers {
server api:8080;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
server {
# SSL configuration
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
ssl_certificate /etc/nginx/server.crt;
ssl_certificate_key /etc/nginx/server.key;
root /var/www/html;
# Add index.php to the list if you are using PHP
index index.html index.htm index.nginx-debian.html;
server_name localhost;
location /ver {
proxy_pass http://app_servers/api/version;
proxy_set_header Host $host;
}
location / {
if ($request_method = OPTIONS ) {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header Access-Control-Allow-Methods "POST, OPTIONS";
add_header Access-Control-Allow-Headers "Accept, Cache-Control, x-csrf-token, Authorization, Content-Type";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
add_header 'Access-Control-Allow-Origin' '*' always;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_pass http://app_servers/graphql;
#
#proxy_redirect off;
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ =404;
}
}
}
此配置与生产服务器之间的唯一区别是,在生产中,proxy_pass
目标是 127.0.0.1 而不是 app_servers,并且服务器名称是实际的服务器名称而不是 localhost。主机名api
来自 docker-compose 中的服务定义。
我遇到的情况是,我可以成功访问 /ver 端点,但任何其他应路由到 api:8080/graphql 的请求都会导致 404。但是,我可以轻松连接到使用 GraphQL 游乐场公开 8080 的 docker 容器并发出请求。
任何见解都将不胜感激,我不是 100% 确信这是一个 Nginx 问题,但所有证据都指向这一点。
答案1
看来解决方案是删除以下几行:
try_files $uri $uri/ =404;
proxy_set_header Host $host;