Skip to content

Instantly share code, notes, and snippets.

@thomasleveil
Created March 7, 2019 21:57
Show Gist options
  • Save thomasleveil/6e9b91a54fbcb43ea75678e3f1f99c2c to your computer and use it in GitHub Desktop.
Save thomasleveil/6e9b91a54fbcb43ea75678e3f1f99c2c to your computer and use it in GitHub Desktop.
Traefik as an automatic reverse proxy in a docker-compose project

Here's a setup using a reverse proxy so that you can use relative url (instead of messing with domain names in your webpages) and which also has the advantage of taking care of CORS issues you would have while making ajax calls to your backend.

If you are not familiar with reverse proxies, just know that all http requests should first hit the reverse proxy, and the reverse proxy will take care of forwarding those http requests to the correct http server following a set of rules.

In the docker world, a very convenient reverse proxy is Traefik.

When Traefik is used with docker, you configure for reverse proxy forwarding rules by adding labels to your docker containers.

version: "3"
services:
reverseproxy: # see https://docs.traefik.io/#the-traefik-quickstart-using-docker
image: traefik
command: --docker
ports:
- "80:80"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
backend:
image: kennethreitz/httpbin # see https://httpbin.org
command: ["gunicorn", "-b", "0.0.0.0:8080", "httpbin:app", "-k", "gevent"]
expose:
- 8080
depends_on:
- reverseproxy
labels:
traefik.frontend.rule: PathPrefixStrip:/api
traefik.port: 8080
frontend:
image: nginx
volumes:
- ./index.html:/usr/share/nginx/html/index.html:ro
expose:
- 80
depends_on:
- reverseproxy
- backend
labels:
traefik.frontend.rule: PathPrefixStrip:/
traefik.port: 80
<!DOCTYPE html>
<html>
<body>
<h2>post a form to backend</h2>
<form action="/api/post" method="post">
<input type="text">
<input type="submit">
</form>
<h2>ajax call to backend</h2>
<button onclick="fetch('/api/json').then(response => response.text()).then(txt => document.getElementById('ajaxresponse').textContent = txt)">click me to make a ajax call to /api/json</button>
<pre id="ajaxresponse"></pre>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment