Docker撰写NGINX反向代理502

时间:2020-01-31 00:17:33

标签: go nginx docker-compose gorilla mux

我具有以下设置,并且终生无法弄清为什么我无法连接到api。

nginx.conf

worker_processes auto;
worker_rlimit_nofile 200000;

events {
  use epoll;
  accept_mutex on;
  multi_accept on;
  worker_connections 1024;
}

http {
  error_log /etc/nginx/error_log.log warn;
  client_max_body_size 20m;

  server {
    listen 80;
    listen [::]:80;

    location / {
      proxy_pass http://api:8080/;
    }

    location /health {
      return 200;
      access_log off;
    }
  }
}

docker-compose.yml

version: "3.7"

services:
  nginx:
    container_name: nginx
    image: "nginx:latest"
    ports:
      - "8000:80"
    networks:
      - internal_net
    volumes:
      - ./container/nginx.conf:/etc/nginx/nginx.conf

  api:
    container_name: api
    build:
      context: .
      dockerfile: container/Dockerfile
    expose:
      - "8080"
    networks:
      - internal_net
    depends_on:
      - postgres
    command: ["./wait-for-it.sh", "postgres:5432", "--timeout=60", "--", "./52-server-go"]

  postgres:
    container_name: postgres
    image: "postgres:9.5-alpine"
    expose:
      - "5432"
    networks:
      - internal_net

networks:
  internal_net:
    driver: bridge

volumes:
  container:

我的api设置为在端口8080上运行,当我进入容器并对该地址运行curl请求时,它可以工作。根据撰写文件,应该将该地址公开给包括nginx在内的所有服务共享的本地撰写网络。

根据nginx配置,它应该将每个请求(有效的/health除外)传递给api服务。相反,返回的是nginx的502。

我在哪里混在一起?我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题实际上出在我的go应用中。使用golang gorilla/mux,必须更改地址:

原始(损坏)

    // Start server
    address := "127.0.0.1:8080"
    srv := &http.Server{
        Handler:      r,
        Addr:         address,
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

修复

    // Start server
    address := "0.0.0.0:8080"
    srv := &http.Server{
        Handler:      r,
        Addr:         address,
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }

我不知道为什么 ,但这已解决。