🐳 Day 5: Mastering docker exec Command - With examples!

Ibrar AnsariIbrar Ansari
4 min read

Welcome to this Docker tutorial! In this guide, we cover the docker exec command. Whether you're new to Docker or just need a refresher, this will help you understand how to run commands inside a running container. Let's dive in! 🎯

🎬 Video Demonstration

Watch on Youtube

πŸ“Œ 1. What is docker exec?

The docker exec command allows you to run a command in a running container.

🧠 It's like opening a terminal inside your container!

❔ Get Help using help command

docker exec --help
Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Execute a command in a running container

Aliases:
  docker container exec, docker exec

Options:
  -d, --detach               Detached mode: run command in the background
      --detach-keys string   Override the key sequence for detaching a container
  -e, --env list             Set environment variables
      --env-file list        Read in a file of environment variables
  -i, --interactive          Keep STDIN open even if not attached
      --privileged           Give extended privileges to the command
  -t, --tty                  Allocate a pseudo-TTY
  -u, --user string          Username or UID (format: "<name|uid>[:<group|gid>]")
  -w, --workdir string       Working directory inside the container

❓ 2. Why Use docker exec?

Here are some common reasons to use docker exec:

  • 🐞 Debugging: Access a container’s shell to troubleshoot issues.

  • πŸ” Inspection: Check files, processes, or environment variables inside a container.

  • πŸ› οΈ Management: Run one-off commands or scripts without modifying the container’s image.

  • πŸ—¨οΈ Interactivity: Start an interactive session (e.g., a bash shell) to work inside the container.

πŸ› οΈ 3. Syntax

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
  • CONTAINER: The name or ID of the running container (find it using docker ps).

  • COMMAND: The command you want to run inside the container.

  • ARG: Optional arguments for the command.

  • OPTIONS:

    • -i, --interactive: Keep STDIN open.

    • -t, --tty: Allocate a pseudo-TTY.

    • -d, --detach: Run the command in the background.

    • -u, --user: Run the command as a specific user.

    • -e, --env: Set environment variables.

    • --workdir: Set the working directory inside the container.

Summery

🧩 -i β†’ Interactive

  • Keeps STDIN (standard input) open even if not attached.

  • Allows you to send input to the container, such as typing commands or piping input.

πŸ–₯️ -t β†’ TTY (Pseudo-TTY)

  • Allocates a pseudo-terminal.

  • Makes the session act like a real terminal β€” this enables features like:

    • Colored output

    • Line editing

    • Clear formatting

Test Case

docker exec -i β€” you can pipe input in, but the terminal behaves oddly.
docker exec -t β€” may hang, since it expects interactive input.
docker exec -it ubuntu apt update -y

πŸš€ 4. Basic Example

Check the current directory inside the container:

docker exec ubuntu pwd

➑️ Use Case: Quickly verify the working directory or check system details.

πŸ–₯️ 5. Open an Interactive Shell

To start a bash shell inside the container:

docker exec -it ubuntu bash
docker exec -it alpine bash

πŸ” If bash isn't available, try sh:

docker exec -it alpine sh

πŸ”’ 6. Run as a Specific User

Run a command as the root user:

docker exec -u root ubuntu whoami

➑️ Use Case: Perform actions requiring elevated permissions.

πŸ“œ 7. Run a Script Inside the Container

To run a script in the background:

docker exec -it ubuntu /root/setup.sh

➑️ Use Case: Execute long-running tasks without tying up your terminal.

🌱 8. Set Environment Variables

Set an environment variable for the command:

docker exec -e user=postgres ubuntu env

➑️ Use Case: Test how environment variables affect a command.

πŸ“‚ 9. Run a Command in a Specific Directory

Run a command in a specific working directory:

docker exec --workdir /root ubuntu pwd
docker exec --workdir /root ubuntu ls -alsh

➑️ Use Case: Execute commands in a specific directory without altering container defaults.

βœ… 10. Best Practices

  • βœ… Always use -it for interactive commands.

  • βœ… Ensure your container is running before executing commands.

  • βœ… Use docker ps to check container status.

  • ❌ Avoid running long-lived processes via exec β€” it's for one-off tasks.


πŸ”— Additional Resources


Happy Docking! πŸ³πŸ’»

0
Subscribe to my newsletter

Read articles from Ibrar Ansari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ibrar Ansari
Ibrar Ansari

Hello! I'm a DevOps Engineer dedicated to continuous learning and contributing to the tech community. If you find value in what I share, feel free to spread the word to others who might benefit as well. Your support is greatly appreciated!