Chapter 2 · Lesson 12 of 20
Docker

Run commands inside a Docker container (docker exec)

docker exec runs a command inside an already running container, which is the normal way to open a shell and inspect it.

By the end you will

Open a shell inside a running container and run one-off commands.

Time
14 min
Level
Beginner
Check
4 questions
You need
  • Docker installed
  • A running container

To run a command inside a running container, use docker exec -it NAME sh. It starts one more process in the container’s own file system and network, so you can read files, test connections and run one-off tasks without rebuilding the image. It only works while the container is running.

How it works#

A container is not a small virtual machine. It is a normal process (or a few) on your server, started with its own view of the file system, network and process list. docker exec starts one more process inside that same isolated view. It joins the container that is already running, so it sees the same files and the same network as the main process.

That has three consequences. First, the container must be running: if the main process has exited, there is nothing to join. Second, the extra process exists only while your command runs. When you type exit, the shell ends and the container keeps going. Third, the command is looked up inside the container’s file system, so it can only run programs that image contains. A minimal image may have no bash, no curl and no ps.

docker compose run is different. It creates a brand new container from the service definition, runs your command there, and stops. It is for one-off jobs, not for looking at the container that is serving traffic.

Step 1: Open a shell in a running container#

Find the name first:

bash
docker ps

What you should see: a table with a NAMES column on the right. Use that name below. Then:

bash
docker exec -it web sh

-i keeps standard input open so you can type. -t allocates a terminal so the shell shows a prompt and handles line editing. Type exit to leave. What you should see: a new prompt, often / # on Alpine-based images, and docker ps still lists the container after you exit.

Step 2: Do the same with Compose#

Use the service name from compose.yaml, not the container name:

bash
docker compose exec web sh

Run this from the folder that holds compose.yaml. What you should see: the same kind of prompt. Compose allocates a terminal by default, so you do not need -it here.

You can also run a single command without an interactive shell:

bash
docker exec web ls /usr/share/nginx/html

What you should see: the file listing printed in your terminal, then control returns to you. For pipes or variables, wrap the command in a shell so the container interprets it, not your host:

bash
docker exec web sh -c 'ls /usr/share/nginx/html | wc -l'

Step 3: Run a one-off container#

compose run starts a new container from a service definition, runs one command and exits:

bash
docker compose run --rm web sh

--rm deletes that temporary container afterwards. Without it, every run leaves a stopped container behind. Use this for tasks such as database migrations. What you should see: a shell inside a fresh container, plus any dependent services (a database, for example) started if they were not already running.

Check it worked#

Inside the shell, run:

bash
hostname
ls /

You should see the container’s own hostname (usually a short hex id) and its own root file system, not your server’s. Typing exit returns you to your normal prompt, and docker ps should still list the container as running.

Edge cases and gotchas#

  • The container is stopped or restarting. docker exec fails on anything not running, with an error that the container is not running. Check docker ps -a and docker logs NAME. To poke at the image anyway, start a throwaway container with docker run --rm -it --entrypoint sh IMAGE.
  • There is no bash. Images built from Alpine, and many “slim” or distroless images, have sh only or no shell at all. A distroless image may have nothing to exec into. Debug those with a separate debug image or by reading logs.
  • Your host shell expands variables first. docker exec web echo $HOME prints your host value. Use docker exec web sh -c 'echo $HOME' with single quotes.
  • You are root inside, but maybe not intended to be. Many images run as a non-root user, and exec uses the image’s user by default. Add -u root to run as root for debugging, and -u appuser to match the app.
  • The working directory is the image default. Use -w /app to start in a specific folder.
  • Two containers, similar names. Compose names containers after the project folder, so two projects can both have a web service. docker compose exec targets the project in your current folder, while docker exec needs the exact container name.
  • Changes are temporary. Files you edit or packages you install live in the container’s writable layer. They vanish when the container is recreated (an image update, docker compose up -d after a config change, or docker rm).

Troubleshooting#

SymptomLikely causeFix
No such container: webWrong name, or the container was removedRun docker ps -a and use the exact name
The container is not runningIt exited or is restartingRead docker logs NAME, fix the cause, start it again
OCI runtime exec failed with executable file not foundThe program, often bash, is not in the imageTry sh, or install tools in your Dockerfile
the input device is not a TTYYou used -t from a script or cron jobDrop -t, keep -i only if you pipe input
no configuration file provided: not foundYou ran docker compose exec outside the project foldercd to the folder with compose.yaml or pass -f
no such service: webThe name is the container name, not the service nameUse the service key from compose.yaml
Package installed earlier is missingThe container was recreatedAdd it to the Dockerfile so it is in the image
Shell opens but curl or ps is missingThe image is minimal and does not ship that toolAdd the tool in your Dockerfile, or test from a second container on the same network
Permission denied when writing a fileThe image runs as a non-root userUse -u root for debugging only, then fix ownership in the Dockerfile

Real-world scenario#

Maya deploys a small web app and gets a 500 error on the login page. The logs say only that the database connection failed. She opens a shell in the service and looks at what the app actually sees.

bash
docker compose exec web sh
env | grep DATABASE

The variable shows DATABASE_HOST=localhost. Inside a container, localhost is the container itself, not the database. She checks that the database name resolves from the same shell:

bash
ping -c 1 db
exit

The name db resolves, so the network is fine and the value is wrong. She changes the variable in compose.yaml (see Compose environment variables), runs docker compose up -d and the login works. She never installed anything in the container, which is why the fix survived the recreate. Before opening a shell, read the output first, see read container logs.

Quick reference#

GoalCommand
Shell in a running containerdocker exec -it NAME sh
Shell via Compose service namedocker compose exec SERVICE sh
One command, no shelldocker exec NAME ls /app
Command with pipesdocker exec NAME sh -c 'ls /app | wc -l'
Run as rootdocker exec -u root -it NAME sh
Set working directorydocker exec -w /app -it NAME sh
One-off new containerdocker compose run --rm SERVICE CMD
Container not runningdocker run --rm -it --entrypoint sh IMAGE

Security and safety notes#

  • A shell in a container runs with that container’s permissions. A container started with --privileged or with the Docker socket mounted gives a shell that can affect the whole host, so be careful what you run there.
  • Do not edit production data by hand in a container without a backup.

Next#

Keep images small with multi-stage Docker builds.

Check what you learned4 questions
1Which command opens a shell in a running container named web?
2You installed a package inside a container, then the container was recreated. What happened to the package?
3OCI runtime exec failed: executable not found for bash. What should you try?
4docker exec web echo $HOME shows your host's home directory, not the container's. Why?

Frequently asked questions

Why does sh work when bash does not?

Small images such as Alpine ship only sh. Try sh first, and use bash when the image includes it.

Are changes I make inside a container permanent?

Only data stored in a volume survives. Other changes are lost when the container is removed and recreated, for example after an image update.

Can I exec into a container that keeps crashing?

No. docker exec only works on a running container. Read docker logs first, or start a throwaway container from the same image with a different command, such as docker run --rm -it --entrypoint sh IMAGE.

Why does my command work in the shell but fail with docker exec?

docker exec does not run a shell for you, so pipes, redirects and wildcards are not expanded. Wrap the command, for example docker exec web sh -c 'ls /app | wc -l'.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios