在docker容器中使用带反向代理的nginx不起作用

我希望以/api开始的所有内容都被定向到http://localhost:3007

这是我的nginx.conf

 user nginx; worker_processes 1; daemon off; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root /usr/html; index index.html index.htm; } location /api { proxy_pass http://localhost:3007; proxy_read_timeout 5m; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } include servers/*; } 

它在我的Mac上本地运行时起作用。 但是当我在docker-container中运行它时,它不起作用。

这是我的docker文件:

 FROM smebberson/alpine-nginx:latest COPY /dist /usr/html/ COPY nginx.conf /etc/nginx/nginx.conf 

这是我的docker组成:

 version: "2" services: web: build: . ports: - "80:80" 

我从nginx得到的错误:

 2017/06/28 13:06:51 [error] 200#0: *9 connect() failed (111: Connection refused) while connecting to upstream, client: 172.19.0.1, server: localhost, request: "GET /api HTTP/1.1", upstream: "http://127.0.0.1:3007/api", host: "localhost" 

最有可能的是,你不需要localhost:3007但像api-upstream-server:3007 – 一个单独的容器运行的应用服务器代码和暴露端口3007。

在容器内, localhost是容器,而不是主机。 Docker将容器与主机节点隔离开来。

但是请注意,您可能还需要在Docker容器中运行其他所有内容(数据库等)。