Knowledge
docker exec: run a command in a running container
#Development
docker exec runs a command inside a container that is already running. The classic use is opening an interactive shell with docker exec -it, but it is just as useful for one-off commands.
Published by Mark van Eijk on June 23, 2026 · 1 minute read
Open a shell inside a container
The most common use of docker exec is getting a shell in a running container. The -it flags give you an interactive terminal:
docker exec -it my-container bash
If the image is minimal and has no bash, fall back to sh:
docker exec -it my-container sh
The -i keeps STDIN open and -t allocates a pseudo-TTY; together they make the shell behave like a normal terminal.
Run a one-off command
You do not need a shell for a single command. Anything after the container name is run inside it:
docker exec my-container ls -la /app
docker exec my-container cat /etc/hostname
For a Laravel container you might run Artisan, or open a database client:
docker exec -it my-app php artisan migrate
docker exec -it my-db mysql -u root -p
Useful flags
docker exec -u www-data my-container whoami # run as a specific user
docker exec -w /app my-container pwd # set the working directory
docker exec -e DEBUG=1 my-container env # pass an environment variable
exec vs run vs attach
These look similar but do different things:
docker execruns a command in a container that is already running.docker runcreates a new container from an image.docker attachconnects to the container's main process (its PID 1), soCtrl+Cthere can stop the container, which is usually not what you want.
To find the container name or ID to pass to exec, list running containers with docker ps. If you started everything with Compose, see docker compose up.
Subscribe to our newsletter
Do you want to receive regular updates with fresh and exclusive content to learn more about web development, hosting, security and performance? Subscribe now!
Related articles
Install PHP memcached extension on macOS
docker exec runs a command inside a container that is already running. The classic use is opening an interactive shell with docker exec -it, but it is just as useful for one-off commands.
How to delete a local (and remote) Git branch
docker exec runs a command inside a container that is already running. The classic use is opening an interactive shell with docker exec -it, but it is just as useful for one-off commands.