Docker nginx在一台主机上有多个应用程序

Axo*_*xon 12 nginx docker docker-compose jwilder-nginx-proxy

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

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

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

Ole*_*yev 7

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"]
Run Code Online (Sandbox Code Playgroud)

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/;
    }
}
Run Code Online (Sandbox Code Playgroud)

** 其中web1web2-容器名称

docker-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
Run Code Online (Sandbox Code Playgroud)

如何运行:

docker-compose up -d
Run Code Online (Sandbox Code Playgroud)

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

PS:您的问题是关于NGINX-反向代理。但是使用TRAEFIK https://traefik.io更好,更轻松地做到这一点

  • 但是然后nginx是单独的容器,不包含在任何docker compose文件中 (2认同)
  • 这似乎对我不起作用,我最终遇到了 502 bad gateway nginx 错误。我做了一些搜索,发现了这个 https://www.thepolyglotdeveloper.com/2017/03/nginx-reverse-proxy-containerized-docker-applications/ ,其中包含以下行 http { sendfile on; 上游 docker-nginx { 服务器 nginx:80; } 上游 docker-apache { 服务器 apache:80; } ....这些有必要吗? (2认同)

Dek*_*vic 5

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

services:
web:
    image: your_image
    container_name: web
    ports:
        - 8080:80
        - 8081:81
Run Code Online (Sandbox Code Playgroud)

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

第一个应用程序

server {
listen 80;
server_name localhost;
root /app/first;
}
Run Code Online (Sandbox Code Playgroud)

第二个应用程序

server {
listen 81;
server_name localhost;
root /app/second;
}
Run Code Online (Sandbox Code Playgroud)

以便:

  • 第一个应用程序访问本地主机:8080
  • 本地主机上的第二个应用程序访问:8081