How to connect two docker containers via docker-compose

How to connect two docker containers via docker-compose

This is a small walkthrough consist of one of the simplest way to connect two containers using docker-compose

What's the need

You can easily start one container and access it using http://localhost:{port} but you can’t call a service running inside a container from another container.

Reason

1200px-Disjunkte_Mengen.png

Let’s assume you have two services: A and B running on ports 8081 and 8082 respectively . If you try to call A on 8081 from inside the B using localhost:8081 then it won’t able to connect on this port because localhost’s context is limited to A container, and it won’t be able to see anything outside of its scope.

docker containers are isolated environments

We have some methods to connect them:

  • Manual Docker Networking ( Let's leave it for another blog )
  • Docker-compose

Docker-compose

Here, You just need to specify different services and later, establish dependency.

Create a file named docker-compose.yml

Here, We're trying to connect selenium/standalone-chrome to mysql container

Steps

  • Specify the version

    version: "3"
    

    Refer here for more details regarding docker versions

  • Define services such as main collector service and mysql database inside services section

    collector:
      image: selenium/standalone-chrome
      container_name: 'chrome'
      ports:
        - 8081:8081
      depends_on:
         - db
    db:
      image: mysql
      container_name: 'database'
      ports:
        - 8082:8082
      volumes:
        - db-address:/var/lib/postgresql/data
    

Following properties explanation:

  • ports : Exposing of container port to host machine
  • depends_on : Express dependency between services.
  • container_name : Naming the container
  • volumes : Mounts source directories or volumes from your computer at target paths inside the container

Refer here for more info regarding service properties.

Finally, your docker-compose.yml should look something like this

version: "3"
services:
  collector:
    image: selenium/standalone-chrome
    container_name: 'chrome'
    ports:
      - 8081:8081
    depends_on:
       - db
  db:
    image: mysql
    container_name: 'database'
    ports:
      - 8082:8082
    volumes:
      - db-address:/var/lib/postgresql/data
volumes:
  db-address:

Final Stage

Fire up the docker

docker-compose up

Screenshot 2022-08-20 at 12.27.41 AM.png

It may take time on first run

Did you find this article valuable?

Support Khushiyant by becoming a sponsor. Any amount is appreciated!