How to Install docker-compose on Ubuntu

How to Install docker-compose on Ubuntu

To run a docker container you can simply use the command: docker run <image name>

However, by using docker-compose, you can defining and running multi-container Docker applications. It uses a YAML file to configure your application's services, networks, and volumes.

Docker Compose relies on Docker to function. If you don't have Docker installed, you can refer to this article: How to install Docker on Ubuntu

Installing Docker-Compose

Here’s how you can install Docker Compose on an Ubuntu system:

sudo apt-get update
sudo apt-get install docker-compose

Install docker-compose

Using Docker-Compose

Now that Docker-Compose is installed, let's explore how to use it. Docker-Compose allows you to define multi-container applications in a docker-compose.yml file and then spin up all the services with a single command.

Here is a basic example for a simple web application:

version: '3'
services:
  web:
    image: mywebsite:latest
    ports:
      - "80:80"
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: example

In this example:

  • The version:3 refer to the format version of the docker-compose.yml file
  • The web service uses the latest version of the mywebsiteimage and maps port 80 on the host to port 80 on the container.
  • The db service uses the latest version of the mysql image and sets an environment variable for the MySQL root password.

To Start the Docker-Compose Application:

sudo docker-compose up

If you want to run the containers in the background (detached mode), use the -d option:

sudo docker-compose up -d

Verify the Application is Running

sudo docker-compose ps

To stop the running services, use:

sudo docker-compose down

View Logs:

sudo docker-compose logs

You can also tail the logs for a specific service:

sudo docker-compose logs -f <service name>

<Service name> is the name in nginx config file

Using Environment Variables:

You can define environment variables in a separate file and reference them in your docker-compose.yml. Create a .env file:

MYSQL_ROOT_PASSWORD=example

.env file

Then, reference it in your docker-compose.yml:

version: '3'
services:
  db:
    image: mysql:latest
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}

Do you enjoy this blog post?

Read more