Docker Compose With Frontend and Backend Network

Problem :

Application is conected to frontend and access database on backend. Database is not accessible to outside world. Appliaction should have to have static ip.

Solution:

Define two separate networks in your Docker Compose file, one for the frontend and one for the backend. You can also assign static IP addresses to your containers using the ipv4_address attribute.

Example:

Here is an example docker-compose.yml file that demonstrates this setup:


version: '3'

networks:
  frontend:
    ipam:
      driver: default
      config:
        - subnet: 172.16.1.0/24
  backend:
    ipam:
      driver: default
      config:
        - subnet: 172.16.2.0/24

services:
  web:
    image: my-app
    networks:
      frontend:
        ipv4_address: 172.16.1.10
      backend:
        ipv4_address: 172.16.2.10
    environment:
      DATABASE_URL: postgres://dbuser:dbpass@database/dbname
    depends_on:
      - database
  
  database:
    image: postgres
    networks:
      backend:
        ipv4_address: 172.16.2.20
    environment:
      POSTGRES_USER: dbuser
      POSTGRES_PASSWORD: dbpass
      POSTGRES_DB: dbname

Explanation:

In the above example, we define two networks, frontend and backend, each with its own subnet. We also define two services, web and database.

The web service is connected to both networks, frontend and backend, with static IP addresses of 172.16.1.10 and 172.16.2.10, respectively. It also has an environment variable DATABASE_URL that references the hostname of the database service.

The database service is connected only to the backend network, with a static IP address of 172.16.2.20.

With this setup, the web service can access the database service using the DATABASE_URL environment variable, and the database service is only accessible within the backend network and is not exposed to the public internet.


Revision #3
Created 2023-05-01 16:06:17 UTC by Dušan Fefer
Updated 2023-05-01 16:15:16 UTC by Dušan Fefer