DEV Community

Kevin Bradwick
Kevin Bradwick

Posted on • Edited on

How to setup a reverse proxy to your host machine using Docker

Recently, I found myself needing a reverse proxy for my local development environment. I had two applications running on different ports, and I wanted them to appear to be served from a single top level domain. This can be useful when you want cookies shared across sub-domains.

For example, I had a single Django application running on port 8000, and a React frontend running on Webpack dev server on 8080. I wanted them both to be accessible from api-app.localhost and web-app.localhost respectively.

Naturally, I turned to Docker for a solution and this is what I came up with. Here is the Docker compose file that uses the Alpine Nginx image to set up the reverse proxy.

It references two Nginx configuration files.

Here's web.conf. You'll notice that there are headers defined that are related to the http version and connection upgrade. This enables Websockets to work that Webpack dev server uses for hot reloading.

And here is the api.conf.

What makes Nginx proxy to your host machine is the use of host.docker.internal in the upstream.

Before starting the containers, there is one thing left to do. Add the two hosts entries to your host file on your host machine. If that's a Linux machine (including macOS) then edit /etc/hosts, and if you are on Windows, edit C:\Windows\System32\drivers\etc\hosts.

127.0.0.1 api-app.localhost web-app.localhost
Enter fullscreen mode Exit fullscreen mode

And now start the containers!

docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

When you start the proxy, and both apps are running on your host machine, you'll be able to reach them on http://web-app.localhost:5000 and http://api-app.localhost:5000.

Enjoy!

Top comments (4)

Collapse
 
jasoki profile image
Jason Kim

Unfortunately host.docker.internal isn't supported on Linux at the moment.
github.com/docker/for-linux/issues...

Collapse
 
caganerd profile image
CaganErd

Thank you for posting. Is there a way to get these services accessible with other devices in the local network with the hosts file? My Services and the Reverse Proxy should be running in Containers with a Ubuntu-PC. I don't want to waste time with the DNS server if it can be solved this way.

Collapse
 
lysofdev profile image
Esteban Hernández

Awesome post! Could you clarify the last step where you added host entries to the hosts file? Is this necessary if the host machine is only for development?

Collapse
 
kevbradwick profile image
Kevin Bradwick

Hi, glad you found it useful. Yes, you'll need to edit the hosts file on your host machine (I've updated the article). And yes, this article is aimed at local development where you need two different apps, running in different processes, to be served from the same top level domain.