提问人:Yelk0 提问时间:7/25/2023 最后编辑:Yelk0 更新时间:7/25/2023 访问量:37
如何使用 proxy_pass 创建一个使用 nginx 的 dockefile,以便在一个容器中为全栈应用程序提供服务?我的目标是使用云运行
How can I create a dockefile that uses nginx using proxy_pass in order to serve a fullstack application in one container? I aim to use cloud run
问:
我的 dockerfile 看起来有点像这样: -- 简化
FROM ubuntu:22.10
# Create my_user ...
# Copy Nginx configuration files
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY ./proxy.conf /etc/nginx/conf.d/proxy.conf
WORKDIR /app
RUN npm install \
&& npm run build
WORKDIR /app/frontend
RUN npm install \
&& npm run build
RUN sudo cp -a ./dist/. /var/www/html
WORKDIR /app
CMD ["sh", "-c", "nginx -g 'daemon off;' & npm run start:prod"]
这是我的proxy.conf
upstream backend {
server localhost:3000;
}
server {
listen 8080;
server_name _;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location ~ \.(css|js)$ {
add_header Content-Type text/plain;
try_files $uri =404;
}
location /api {
proxy_pass http://backend/api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
这是我的nginx.conf
user my_user;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# Other event configurations if needed
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
sendfile on;
include /etc/nginx/conf.d/*.conf;
}
在本地,这就像一个魅力,但是一旦部署在云中运行并尝试访问 /api 下的路径,例如 my_domain.bla/api/here/we/are,我从 nginx 得到一个日志说:
[error] 10#10: *9 connect() failed (111: Connection refused) while connecting to upstream, client: #certain_IP, server: _, request: "GET /api/here/we/are HTTP/1.1", upstream: "http://127.0.0.1:3000/api/here/we/are", host: "my_domain.bla""
Nginx 正在侦听端口 8080,我的后端应用程序在端口 3000 上运行(我看到来自容器的清晰日志确认应用程序运行良好并侦听正确的端口)
我希望proxy_pass能像在本地一样在云上运行。有人了解云运行和本地运行之间的区别吗? 我的第一个想法是 nginx 可能尝试将请求路由到主机而不是内部容器。后端端口没有公开,所以它会解释连接被拒绝,但我该如何解决?
答:
评论