Docker nginx multiple apps on one host

Axon picture Axon · Mar 26, 2018 · Viewed 22.3k times · Source

I'm confused by how I should manage reverse proxy (nginx) with multiple independent webapps on the same host. I know that i can use https://github.com/jwilder/nginx-proxy and configure VIRTUAL_HOST per app but then I wont be able to have nginx visible as a service in every app docker-compose.yml.

I want to do it this way because I want to clearly define all services needed to run app in production and replicate it easy in development.

In other words: I have two webapps that I need to run on the same host and I want to define nginx as a service dependency in docker-compose.yml in both apps but share that service with both as only one nginx can forward port 80.

Answer

Oleh Vasylyev picture Oleh Vasylyev · Mar 26, 2018

Dockerfile:

FROM ubuntu:14.04
MAINTAINER Test ([email protected])
# 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/;
    }
}

** where web1 and web2 - container names

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

How to run:

docker-compose up -d

When you call test1.com - nginx forwards your request to container web1:81, when test2.com - to container web2:82

P.S.: your question was about NGINX-reverse-proxy. But better and easier do this with TRAEFIK https://traefik.io