为什么我收到:502 Bad Gateway?

时间:2018-05-04 05:40:56

标签: node.js docker nginx

我有这个Dockerfile用于与nginx一起部署我的nodejs应用程序:

    #Create our image from Node
FROM node:latest as builder

MAINTAINER Cristi Boariu <cristiboariu@gmail.com>

# use changes to package.json to force Docker not to use the cache
# when we change our application's nodejs dependencies:
ADD package.json /tmp/package.json
RUN cd /tmp && npm install
RUN mkdir -p /opt/app && cp -a /tmp/node_modules /opt/app/

# From here we load our application's code in, therefore the previous docker
# "layer" thats been cached will be used if possible
WORKDIR /opt/app
ADD . /opt/app

EXPOSE 8080

CMD npm start

### STAGE 2: Setup ###

FROM nginx:1.13.3-alpine

## Copy our default nginx config
RUN mkdir /etc/nginx/ssl
COPY nginx/default.conf /etc/nginx/conf.d/
COPY nginx/star_zuumapp_com.chained.crt /etc/nginx/ssl/
COPY nginx/star_zuumapp_com.key /etc/nginx/ssl/

RUN  cd /etc/nginx && chmod -R 600 ssl/

RUN mkdir -p /opt/app

EXPOSE 80 443

CMD ["nginx", "-g", "daemon off;"]

这是我的nginx文件:

    upstream api-server {
    server 127.0.0.1:8080;
}

server {
    listen 80;
    server_name example.com www.example.com;
    access_log /var/log/nginx/dev.log;
    error_log /var/log/nginx/dev.error.log debug;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://api-server;
        proxy_redirect off;
    }
}

server {
    listen 443 default ssl;

    server_name example.com www.example.com;

    ssl on;

    ssl_certificate /etc/nginx/ssl/star_example_com.chained.crt;
    ssl_certificate_key /etc/nginx/ssl/star_example_com.key;
    server_tokens off;

    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
    ssl_prefer_server_ciphers on;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarder-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_pass http://api-server;
        proxy_redirect off;
    }
}

我已经花了几个小时调试这个没有成功。

基本上,我收到:

  

502 Bad Gateway

尝试在本地测试时:

https://localhost/docs/#

来自泊坞日志:

    172.17.0.1 - - [04/May/2018:05:35:36 +0000] "GET /docs/ HTTP/1.1" 502 166 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1 Safari/605.1.15" "-"
2018/05/04 05:35:36 [error] 7#7: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.17.0.1, server: example.com, request: "GET /docs/ HTTP/1.1", upstream: "http://127.0.0.1:8080/docs/", host: "localhost"

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

你应该配置:

server 172.17.42.1:8080; 

172.17.42.1是docker的网关IP地址。

server app_ipaddress_container:8080;

在nginx.conf文件中。

由于端口8080是在主机上侦听的,而不是在容器上侦听。