Executing a Command in a Docker Compose Container Using the Ubuntu Console

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Continuing with the Docker tutorials, I will explain how we can execute a command inside a Docker container using the Ubuntu console.

If we have this example Docker Compose taken from the tutorial Deploying Apache Web Server with PHP using Docker Compose

version: "3"
# Indicate the Docker Compose version we are using
# Then specify the services we are going to implement
services:
  # Choose the desired name here
  mi_servicio_apache:
    # Image of APACHE with PHP
    image: php:7.0-apache
    container_name: apache-container
    volumes:
      # Folder where we will store the web files: internal Docker folder
      - ./www/:/var/www/html
    expose:
      # Port we want to expose to share it with other containers
      - 80
    ports:
      # Our machine's port: Docker's port (always 80 for Apache or 443 for SSL)
      - 80:80

With this command, we can execute any command inside a Docker container:

sudo docker exec apache-container service apache2 reload

The command works as follows: first, we use Docker exec, and then we specify the name of the Docker Compose container. The container name is indicated in the field container_name: apache-container within our docker-compose.yml file. In this example, I’m reloading apache2, but we can even install or update packages inside the container.

If we want to copy files from the machine to the Docker container, we need to use the following command:

sudo docker cp /index.html apache-container:/var/www/html/index.html

In this example, we are copying a file named index.html from our machine’s root (where we execute this command) to the var/www/html/index.html folder inside the apache-container of our Docker Compose.

If we want to perform the reverse process, we use the following:

sudo docker cp apache-container:/index.html /var/www/html/index.html

In this case, we copy the file from the root directory of the container’s path (we can use ls to see the path) to the /var/www/html/ directory on our machine.

Leave a Comment