Skip to main content

How to get URLs valid inside and outside of a docker-compose network

· 2 min read

How to get URLs valid inside and outside of a docker-compose network

Docker is used in development to reduce the initial ramp-up time. Especially in setups where multiple services need to communicate, Docker with Docker Compose is not that uncommon. Here’s a neat trick I found today, that allows you to use the same URLs inside the Docker Compose network and on your local machine ✨

Let's assume our application consists of three services:

  • web, a client application which runs in the browser, talks to the API and loads files from “localstack”
  • api, an HTTP JSON API
  • localstack, an AWS S3 replacement

The web app expects to receive file URLs from the api that it can resolve. The api in turn has just one environment variable to configure the location of the localstack app. This means, when we try to access files on localstack from our development machine (in the browser) and from inside the Docker context (the api) it needs to work with the same name.

The trick to achieve this, was to use a .localhost domain, which is usually resolved to the loopback address This means, ports exposed from Docker containers are accessible via http://<some-name>.localhost:<exposed-port> from one's own machine outside the Docker network. Inside the Docker Compose network configuration, you can add a network alias:

# docker-compose.yml

- "4572:4572"
- "localstack.localhost"

S3_URL: "http://localstack.localhost:4572"
# define the network

This way, the same hostname + port combination is resolved to the same service inside your Docker Compose network as well as from the outside (in your browser). So you can avoid additional URL mapping in API responses. ✌️



High-priest to the browser gods

We're hiring

Work with our great team, apply for one of the open positions at bitcrowd