How to Run Multiple Containers with Docker Compose

How to Run Multiple Containers with Docker Compose

Using Docker Compose to run several containers is common, especially for apps made of multiple services. Docker Compose lets you create and run multi-container Docker apps with a YAML file. Here's a simple guide on running multiple containers with Docker Compose:

Step 1: Install Docker Compose

Make sure you have Docker Compose installed. You can download it from the official Docker website: Install Docker Compose

Step 2: Create a Docker Compose YAML File

Make a docker-compose.yml file in your project folder. This file sets up the services, networks, and storage for your app. Here's a basic example with two services (a web app and a database):

version: '3'

services:
  web:
    image: nginx:latest
    ports:
      - "80:80"

  db:
    image: postgres:latest
    environment:
      POSTGRES_PASSWORD: example_password
    ports:
      - "5432:5432"

In this example, there are two services: web (running Nginx) and db (running PostgreSQL). The ports section maps the container ports to the host.

Step 3: Run Docker Compose

Open a terminal, navigate to the directory containing your docker-compose.yml file, and run the following command:

docker-compose up

This command downloads the needed images (if they're not already there) and starts the containers listed in the docker-compose.yml file.

Step 4: Access Your Application

Once the containers are running, you can access your application. In this example, you can access Nginx at http://localhost and PostgreSQL at localhost:5432.

Additional Commands:

  • To run containers in the background, use the -d flag:

      docker-compose up -d
    
  • To stop and remove the containers:

      docker-compose down
    

These are simple steps, and you can add more settings, dependencies, and services to your docker-compose.yml file based on what your application needs.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!