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.

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 NAMES column.

Once run, a new shell will open up, giving us access to the new bash session.

Handling the OCI Runtime Exec Failed Bash Error

Note that /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 sh or /bin/sh to access the shell.

Accessing 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

or

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 sh -c.

docker exec -it CONTAINER_NAME_OR_ID sh -c "command1 && command2"

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

Use Case

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"