How to Execute a Shell Command Immediately Inside a Docker Container
I’ve recently been finding the need to run shell commands inside active, running containers.
Naturally, the first step is to log into the interactive shell of the container.
Access Interactive Shell
We can do this using
docker exec -it CONTAINER_NAME_OR_ID /bin/bash
We can find the
CONTAINER_NAME_OR_ID by listing all docker containers.
docker container ls
And then looking under the
Once run, a new shell will open up, giving us access to the new
OCI Runtime Exec Failed Bash Error
/bin/bash is not installed on every system. For instance, I noticed that it was not available in
node:alpine images, which means I had to use
/bin/sh to access the shell.
bash in a container that does not have it installed will return an error like this.
OCI runtime exec failed: exec failed: container_linux.go:367: starting container process caused: exec: "bash": executable file not found in $PATH: unknown
We can circumvent this issue with either of the following commands.
docker exec -it CONTAINER_NAME_OR_ID sh
docker exec -it CONTAINER_NAME_OR_ID /bin/sh
Immediately Execute a Command
We can immediately execute a shell command after accessing the container shell using
docker exec -it CONTAINER_NAME_OR_ID sh -c "command1 && command2"
-c option forces the command to be read from the following argument string that we provided (
command1 && command2).
If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters. The assignment to $0 sets the name of the shell, which is used in warning and error messages.
This is especially helpful in my current project, where I’m using Prisma in a Next.js application. An update to the Prisma schema requires a
prisma migrate inside the running container.
I can simply run the following to trigger the migration immediately.
docker exec -it next_container_id sh -c "npx prisma migrate dev"
More Docker Articles
- How to Set a Default Environment Variable in docker-compose.yml
- How to Integrate Stripe CLI with Next.js inside Docker Containers
- How to Remove All Docker Images Locally
- How to Fix "Port is already allocated" Error in Docker
- How to Develop with TypeScript in Docker with Hot Reloading
- How to Build TypeScript for Production in Docker
- How to Secure a Docker Container with Distroless Images
- How to Access Environment Variables in React Production Build
- How to Dockerize the MERN Stack for Development
- How to Dockerize a Node.js/Mongo App with Live Reload (nodemon)
- How to Update Docker Containers on File Change