20

我对如何在同一主机上使用多个独立的 webapp 管理反向代理 (nginx) 感到困惑。我知道我可以使用https://github.com/jwilder/nginx-proxy并为每个应用程序配置 VIRTUAL_HOST 但是我将无法让 nginx 在每个应用程序 docker-compose.yml 中作为服务可见。

我想这样做是因为我想清楚地定义在生产中运行应用程序所需的所有服务,并在开发中轻松复制它。

换句话说:我有两个需要在同一主机上运行的 web 应用程序,我想在两个应用程序的 docker-compose.yml 中将 nginx 定义为服务依赖项,但与两者共享该服务,因为只有一个 nginx 可以转发端口 80 .

4

2 回答 2

12

Dockerfile:

FROM ubuntu:14.04
MAINTAINER Test (test@example.com)
# install nginx
RUN apt-get update -y
RUN apt-get install -y python-software-properties
RUN apt-get install -y software-properties-common
RUN add-apt-repository -y ppa:nginx/stable
RUN apt-get update -y
RUN apt-get install -y nginx
# deamon mode off
RUN echo "\ndaemon off;" >> /etc/nginx/nginx.conf
RUN chown -R www-data:www-data /var/lib/nginx
# volume
VOLUME ["/etc/nginx/sites-enabled", "/etc/nginx/certs", "/var/log/nginx"]
# expose ports
EXPOSE 80 443
# add nginx conf
ADD nginx.conf /etc/nginx/conf.d/default.conf
WORKDIR /etc/nginx
CMD ["nginx"]

nginx.conf:

server {
    listen          80;
    server_name     test1.com www.test1.com;
    location / {
        proxy_pass  http://web1:81/;
    }
}
server {
    listen          80;
    server_name     test2.com www.test2.com;
    location / {
        proxy_pass  http://web1:82/;
    }
}

**其中web1web2 - 容器名称

码头工人-compose.yml:

version: "2"
services:
    web1:
        image: your_image
        container_name: web1
        ports:
            - 81:80
    web2:
        image: your_image
        container_name: web2
        ports:
            - 82:80
    nginx:
        build: .
        container_name: nginx
        ports:
            - 80:80
            - 443:443
        links:
            - web1
            - web2

如何运行:

docker-compose up -d

当您调用 test1.com - nginx 将您的请求转发到容器 web1:81,当 test2.com - 到容器 web2:82

PS:你的问题是关于 NGINX-reverse-proxy。但是使用 TRAEFIK https://traefik.io可以更好、更轻松地做到这一点

于 2018-03-26T14:48:19.427 回答
4

您还应该能够在同一个容器中打开两个端口

services:
web:
    image: your_image
    container_name: web
    ports:
        - 8080:80
        - 8081:81

并且在 nginx 站点启用(或 conf.d)中为第二个应用程序添加新的配置文件,它将监听 81 端口。

第一个应用程序

server {
listen 80;
server_name localhost;
root /app/first;
}

第二个应用

server {
listen 81;
server_name localhost;
root /app/second;
}

以便:

  • 本地主机上的第一个应用程序访问:8080
  • localhost:8081 上的第二个应用程序访问
于 2020-04-27T20:16:18.913 回答