How to Run Commands in a Docker Container

By Chandrashekhar Fakirpure

Updated on Aug 09, 2024

In this tutorial, we'll learn how to run commands in a Docker container using docker exec command.

The docker exec command allows you to run commands inside a running Docker container. This can be useful for debugging, running administrative tasks, or interacting with the application running inside the container.

This post provides a straightforward guide on automating the installation of the Nginx web server inside a Docker container using a simple Bash script. It walks through the steps of checking if Docker is installed and running, creating an Nginx container, and installing additional packages inside the container using docker exec.

The script ensures that Nginx is properly set up and accessible, offering an easy way to manage the web server in a Dockerized environment. Whether you're setting up a new Nginx server or maintaining an existing one, this guide helps streamline the process with a focus on simplicity and efficiency.

Prerequisites

  • Docker installed dedicated server or KVM VPS.
  • At least one running Docker container.
  • Basic Linux commands knowledge.
  • A root user access or normal user with administrative privileges.

Step 1: List Running Containers

Before you can use docker exec, you need to know the container ID or name. You can list all running containers using the following command:

docker ps

This will output a list of running containers along with their names and IDs.

Step 2: Running a Command in a Container

The basic syntax for running a command in a Docker container is:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
  • OPTIONS: Additional options like -it for interactive mode.
  • CONTAINER: The name or ID of the container.
  • COMMAND: The command you want to run inside the container.
  • ARG: Optional arguments for the command.

Example 1: Run a simple ls command inside a container:

docker exec CONTAINER_NAME ls

Replace CONTAINER_NAME with the actual name or ID of your container.

Step 3: Running Commands in Interactive Mode

If you want to interact with the command, use the -it option. This is useful for commands like bash, where you need to input commands manually.

Example 2: Open a Bash shell inside the container:

docker exec -it CONTAINER_NAME /bin/bash

This will drop you into an interactive Bash shell inside the container, where you can run additional commands.

Step 4: Running Commands as a Different User

By default, docker exec runs commands as the root user. If you want to run a command as a different user, use the -u option followed by the user ID (UID) or username.

Example 3: Run a command as the user www-data:

docker exec -u www-data CONTAINER_NAME whoami

This will output www-data, indicating that the command was run as that user.

Step 5: Running Background Commands

If you want to run a command in the background without attaching to it, use the -d option.

Example 4: Run a background process inside the container:

docker exec -d CONTAINER_NAME /path/to/background-script.sh

The command will run in the background, and you won't see any output in your terminal.

Step 6: Checking the Exit Status

To check the exit status of a command run with docker exec, you can use the following command:

echo $?

A status of 0 indicates success, while any other number indicates an error.

Bash Script to Install Nginx on Docker

Here's a simple Bash script to install the Nginx web server inside a running Docker container. This script will first check if Docker is installed and running, create a new container from the official Nginx image if needed, and then use docker exec to install any additional packages inside the container.

Bash Script: install_nginx_in_docker.sh

nano install_nginx_in_docker.sh

Add following content:

#!/bin/bash

# Script to install Nginx web server inside a Docker container

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if Docker service is running
if ! systemctl is-active --quiet docker; then
    echo "Docker is not running. Please start Docker service."
    exit 1
fi

# Set container name
CONTAINER_NAME="nginx_container"

# Check if the container already exists
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
    echo "Container '$CONTAINER_NAME' is already running."
else
    # Create a new Nginx container
    echo "Creating a new Nginx container..."
    docker run -d --name $CONTAINER_NAME -p 8080:80 nginx
    echo "Nginx container '$CONTAINER_NAME' created and running on port 8080."
fi

# Install any additional packages (e.g., curl)
echo "Installing curl inside the Nginx container..."
docker exec $CONTAINER_NAME apt-get update
docker exec $CONTAINER_NAME apt-get install -y curl

# Check if Nginx is running properly inside the container
echo "Checking Nginx status inside the container..."
docker exec $CONTAINER_NAME curl -I localhost

echo "Nginx setup inside Docker container completed."

Save and exit the file.

How to Use the Script

Save the Script: Save the script as install_nginx_in_docker.sh.

Make the Script Executable: Run the following command to make the script executable:

chmod +x install_nginx_in_docker.sh

Run the Script: Execute the script by running:

./install_nginx_in_docker.sh

What the Script Does

  • Checks Docker: Ensures Docker is installed and running on the host system.
  • Container Management: If the Nginx container is not already running, it creates a new container from the official Nginx image and maps port 8080 on the host to port 80 in the container.
  • Package Installation: Uses docker exec to install curl inside the running container.
  • Verification: Uses docker exec and curl to check if Nginx is properly serving content inside the container.

This script provides a quick and automated way to set up and interact with an Nginx web server inside a Docker container. You can access Nginx using http://server_ip:8080

Troubleshooting Common Issues

When using the docker exec command, you may encounter a few common errors:

Error: No such container: container-name

The No such container error means the specified container does not exist, and may indicate a misspelled container name. Use docker ps to list your running containers and double-check the name.

Error response from daemon: Container is not running

This not running message means the container exists but is stopped. You can start the container with docker start container-name

Error response from daemon: Container container-name is paused, unpause the container before exec

The Container is paused error explains the problem fairly well. Before proceeding, you need to unpause the container with docker unpause container-name.

Conclusion

In this tutorial, we've seen how to run commands in a Docker container. The docker exec command is a powerful tool for managing and interacting with running Docker containers. Whether you're debugging, performing maintenance, or exploring the container's environment, docker exec provides the flexibility to run commands in real-time.