# 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.

URL: https://levelrail.com/learn/docker/run-commands-inside-a-container/
Updated: 2026-11-27

To run a command inside a running [container](https://levelrail.com/learn/glossary/#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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `No such container: web` | Wrong name, or the container was removed | Run `docker ps -a` and use the exact name |
| The container is not running | It exited or is restarting | Read `docker logs NAME`, fix the cause, start it again |
| `OCI runtime exec failed` with executable file not found | The program, often `bash`, is not in the image | Try `sh`, or install tools in your Dockerfile |
| `the input device is not a TTY` | You used `-t` from a script or cron job | Drop `-t`, keep `-i` only if you pipe input |
| `no configuration file provided: not found` | You ran `docker compose exec` outside the project folder | `cd` to the folder with `compose.yaml` or pass `-f` |
| `no such service: web` | The name is the container name, not the service name | Use the service key from `compose.yaml` |
| Package installed earlier is missing | The container was recreated | Add it to the Dockerfile so it is in the image |
| Shell opens but `curl` or `ps` is missing | The image is minimal and does not ship that tool | Add the tool in your Dockerfile, or test from a second container on the same network |
| `Permission denied` when writing a file | The image runs as a non-root user | Use `-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](https://levelrail.com/learn/docker/docker-networks-explained/)) is fine and the value is wrong. She changes the variable in `compose.yaml` (see [Compose environment variables](https://levelrail.com/learn/docker/docker-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](https://levelrail.com/learn/deploy-operate/read-container-logs/)).

## Quick reference

| Goal | Command |
| --- | --- |
| Shell in a running container | `docker exec -it NAME sh` |
| Shell via Compose service name | `docker compose exec SERVICE sh` |
| One command, no shell | `docker exec NAME ls /app` |
| Command with pipes | `docker exec NAME sh -c 'ls /app \| wc -l'` |
| Run as root | `docker exec -u root -it NAME sh` |
| Set working directory | `docker exec -w /app -it NAME sh` |
| One-off new container | `docker compose run --rm SERVICE CMD` |
| Container not running | `docker 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.

## Related lessons

- [Docker Compose basics](https://levelrail.com/learn/docker/docker-compose-basics/)): how services and the project folder are named
- [Docker volumes and persistent data](https://levelrail.com/learn/docker/docker-volumes-and-persistent-data/)): keep data that exec edits would lose
- [Docker networks explained](https://levelrail.com/learn/docker/docker-networks-explained/)): why service names resolve inside containers
- [Read container logs](https://levelrail.com/learn/deploy-operate/read-container-logs/)): look at output before opening a shell

## Next

Keep images small with [multi-stage Docker builds](https://levelrail.com/learn/docker/multi-stage-docker-builds/)).

## 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

- [Docker docs, docker container exec](https://docs.docker.com/reference/cli/docker/container/exec/)
