My websites running in docker containers, how to implement virtual host?

Rob L picture Rob L · Apr 8, 2015 · Viewed 22.1k times · Source

I am running two websites in two docker containers respectively in a vps. e.g. www.myblog.com and www.mybusiness.com

How can I implement virtualhost in the vps so that the two websites can both use port 80.

I asked this question somewhere else, and was suggested to take a look at: https://github.com/hipache/hipache and https://www.tutum.co/ They look a bit curving. I am trying to find if there is a straightforward way to achieve that. Thanks!

In addition, forgot to mention my vps is a Ubuntu 14.04 box.

Answer

krebernisak picture krebernisak · Apr 8, 2015

Take a look at jwilder/nginx-proxy project.

Automated nginx proxy for Docker containers using docker-gen

It's the easiest way to proxy your docker containers. You don't need to edit the proxy config file every time you restart a container or start a new one. It all happens automatically for you by docker-gen which generates reverse proxy configs for nginx and reloads nginx when containers are started and stopped.

Usage

To run it:

$ docker run -d -p 80:80 -v /var/run/docker.sock:/tmp/docker.sock \
jwilder/nginx-proxy

Then start any containers you want proxied with an env var VIRTUAL_HOST=subdomain.youdomain.com

$ docker run -e VIRTUAL_HOST=foo.bar.com  ...

Provided your DNS is setup to forward foo.bar.com to the a host running nginx-proxy, the request will be routed to a container with the VIRTUAL_HOST env var set.

Multiple Ports

If your container exposes multiple ports, nginx-proxy will default to the service running on port 80. If you need to specify a different port, you can set a VIRTUAL_PORT env var to select a different one. If your container only exposes one port and it has a VIRTUAL_HOST env var set, that port will be selected.