Run A Command On A Docker Container

7 min read

Running a command on a Docker container is one of the most fundamental skills you need when working with containerized applications. In practice, whether you want to inspect files, check logs, install packages, or debug an issue, knowing how to execute commands inside a container gives you full control over your environment. Practically speaking, docker provides two primary tools for this job: docker run for creating a new container and executing a command, and docker exec for running a command inside an already running container. This article walks you through both approaches with clear examples, best practices, and troubleshooting tips so you can confidently manage your containers from the command line.

Understanding the Two Main Ways to Run Commands on a Docker Container

Before diving into syntax, it helps to distinguish between the two scenarios you will encounter. The first is when you need to start a new container and immediately run a command inside it. The second is when a container is already running and you want to execute an additional command without stopping or restarting it That's the part that actually makes a difference..

  • docker run – creates and starts a new container from an image, then runs a specified command.
  • docker exec – runs a command inside an existing, running container.

Mixing up these commands is a common source of confusion. Remember: docker run is for new containers, while docker exec is for containers that are already up and running Easy to understand, harder to ignore. Took long enough..

How to Run a Command in a New Docker Container (docker run)

The docker run command is the entry point for launching containers. Its basic syntax is:

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

If you omit the COMMAND, Docker uses the default command defined in the image. But you can override it by supplying your own command after the image name.

Simple Example: Echo a Message

Suppose you want to run a one-off command using the Ubuntu image. You can do:

docker run ubuntu echo "Hello from inside the container"

Docker will pull the Ubuntu image if it is not already present, create a new container, run echo, print the message, and then exit. The container stops immediately after the command finishes.

Interactive and Detached Modes

Two flags are especially important when running commands:

  • -it – combines -i (interactive) and -t (allocate a pseudo-TTY). This lets you interact with the command, such as opening a shell.
  • -d – runs the container in detached mode (in the background).

Take this: to start an Ubuntu container and open an interactive Bash shell:

docker run -it ubuntu bash

You will land inside the container’s shell, where you can run any command as if you were on a regular Linux machine. Type exit to leave and stop the container The details matter here..

If you want the container to keep running in the background while you execute a long-running process, use -d:

docker run -d --name my_web_server nginx

This starts an Nginx container named my_web_server in the background. You can then use docker exec to run commands inside it Easy to understand, harder to ignore..

Cleaning Up with --rm

The moment you run short-lived commands, the container remains on disk after it exits. To automatically remove the container when it stops, add the --rm flag:

docker run --rm ubuntu echo "This container will be removed automatically"

This is a good habit for one-off tasks and helps keep your system clean.

How to Run a Command in an Existing Docker Container (docker exec)

Once a container is running, docker exec is your go-to tool. Its syntax is:

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

The CONTAINER can be a container name or ID. You can find running containers with docker ps.

Basic Example: List Files

Assume you have a running container named my_web_server. To list the files in its working directory:

docker exec my_web_server ls -la

The output appears in your terminal, but the command runs inside the container’s environment.

Opening an Interactive Shell

One of the most common uses of docker exec is to open a shell inside a running container for debugging or exploration:

docker exec -it my_web_server bash

If the container does not have Bash (e.g., Alpine Linux), use sh instead:

docker exec -it my_web_server sh

The -it flags are essential here—without them, you will not get an interactive terminal.

Running Commands as a Specific User

By default, docker exec runs commands as the user defined in the image (often root). You can specify a different user with the -u flag:

docker exec -u www-data my_web_server whoami

This is useful for testing permissions or running scripts under the correct account.

Common Use Cases for docker exec

  • Inspecting environment variables: docker exec my_container env
  • Checking network connectivity: docker exec my_container ping -c 4 google.com
  • Viewing logs inside the container: docker exec my_container cat /var/log/app.log
  • Installing a debugging tool temporarily: docker exec my_container apt-get update && apt-get install -y curl
  • Running database migrations: docker exec my_db_container python manage.py migrate

Practical Examples and Best Practices

To get the most out of running commands on Docker containers, keep these practices in mind:

  • Prefer docker exec for running containers. Avoid restarting a container just to run a command.
  • Use --rm with docker run for disposable tasks. This prevents clutter from stopped containers.
  • Name your containers. Using --name makes it easier to reference them later with docker exec.
  • Avoid running as root when possible. Use the -u flag to run commands as a non-privileged user, especially in production.
  • Be cautious with interactive shells. Leaving a shell open inside a container can consume resources; exit when done.
  • Check container status first. docker exec only works on running containers. Use docker ps to verify.

Troubleshooting Common Issues

Even experienced users run into problems. Here are solutions to frequent errors:

  • “Container is not running”

  • “Container is not running”: docker exec only works on containers that are actively running. Verify the status with docker ps. If the container is stopped, start it using docker start <container_name> or docker restart <container_name>, then retry your command It's one of those things that adds up. But it adds up..

  • “executable file not found in $PATH”: This error means the binary you’re trying to execute isn’t installed inside the container. Many images are minimal and lack tools like curl, vim, or even bash. On Alpine-based images, use sh instead of bash. You can install tools temporarily with the container’s package manager, but avoid baking debugging utilities into production images It's one of those things that adds up..

  • “permission denied”: You may be attempting to read or write to files owned by another user. Use the -u flag to run the command as the appropriate user, or adjust ownership and permissions inside the container before retrying.

  • OCI runtime exec failed: This often occurs when a container is paused or in an unhealthy state. Unpause it with docker unpause <container_name>, or check docker inspect <container_name> to diagnose deeper state issues. If the container is in a crash loop, docker exec will not work until the main process stabilizes.

  • Interactive shell exits immediately: If docker exec -it <container> bash closes right away, the container may not have bash installed, or its entrypoint may have already terminated. Try sh instead, or confirm the container is still running with docker ps. In CI/CD pipelines, omit -it since there is no attached terminal Simple, but easy to overlook..

  • No output from a command: The command may have executed successfully but produced no standard output. Redirect output to a file inside the container, or append echo "exit code: $?" to verify the command completed Still holds up..

Conclusion

docker exec is an essential tool for debugging, inspecting, and managing running containers without interrupting their primary processes. Treat interactive shells as temporary debugging sessions, prefer non-root users where possible, and rely on docker ps to confirm a container is running before executing commands. That's why by using the right flags, targeting the correct user, and verifying container state beforehand, you can safely execute commands in both development and production environments. With these practices, docker exec becomes a reliable and efficient part of your Docker workflow Surprisingly effective..

Worth pausing on this one.

Out the Door

This Week's Picks

More in This Space

Good Reads Nearby

Thank you for reading about Run A Command On A Docker Container. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home