Skip to main content

Creating Linked Services in Docker Compose: A Guide to Editing docker-compose.yml Files

Updated by Tim Rabbetts on
Link Containers in Docker Compose File

Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you can create a YAML file to configure your application’s services, networks, and volumes, and then use a single command to create and start all the services. Linking containers is an essential task when you are working with applications that involve multiple services that need to communicate with each other.

Creating a docker-compose.yml File

To link containers, you first need to define a docker-compose.yml file that specifies all the services that make up your application. Here is a basic example of how you might define a simple web application and a database:

                
version: '3.8'
services:
  db:
    image: postgres
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - backend
  web:
    build: .
    ports:
      - "8000:8000"
    depends_on:
      - db
    networks:
      - backend
      - frontend

networks:
  backend:
    driver: bridge
  frontend:
    driver: bridge

volumes:
  db-data:
                
            

In this example, two services db and web are defined. The db service uses the PostgreSQL image and the web service builds from the current directory.

Linking Containers Through Networks

In Docker Compose, containers are linked by default if they are part of the same network. In the example above, we defined two networks: backend and frontend. Both containers are connected to the backend network, allowing them to communicate with each other.

The depends_on option is used to express dependency between services, where the web service will wait for the db service to start first.

Communication Between Containers

Containers on the same network can communicate with each other using the service name as the hostname. For instance, the web service can connect to the database by referencing db as the host name in connection strings.

Conclusion

Linking containers in Docker Compose is straightforward thanks to the network configuration. By defining services in the same network, Docker handles the linking of containers automatically, allowing services to communicate securely and efficiently.

Add new comment