The
docker container exec command allow you to execute a command in a running container:
$ docker container exec --help
Usage: docker container exec [OPTIONS] CONTAINER COMMAND [ARG...]
Execute a command in a running container
Aliases:
docker container exec, docker exec
Options:
-d, --detach Detached mode: run command in the background
--detach-keys string Override the key sequence for detaching a container
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
-i, --interactive Keep STDIN open even if not attached
--privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
-u, --user string Username or UID (format: "<name|uid>[:<group|gid>]")
-w, --workdir string Working directory inside the container
Let's check the running container:
$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
8799a7ae86f4 ubuntu:latest "sleep infinity" 4 hours ago Up 4 hours ubuntu-latest
We can execute a specific commands (foreground) in the container:
$ docker container exec 8799a7ae86f4 id
uid=0(root) gid=0(root) groups=0(root)
$
$ docker container exec 8799a7ae86f4 cat /etc/hosts
127.0.0.1 localhost
172.17.0.2 ffd0458ac5e8
$
Using the pipe character (
|) outside of the docker exec command causes the piping to occur on the host, not within the container.
We can use the pipe character (
|) to connect the output of one command to another,
but be aware that the piping will occur on the host, not within the container.
To perform piped operations within the container, wrap the full command in quotes and use
/bin/bash -c:
$ docker container exec 8799a7ae86f4 /bin/bash -c "cat /etc/hosts | grep 127.0.0.1"
127.0.0.1 localhost
$
The same, if we want to run multiple commands inside the container:
$ docker container exec 8799a7ae86f4 /bin/bash -c "id; cat /etc/hosts | grep 127.0.0.1"
uid=0(root) gid=0(root) groups=0(root)
127.0.0.1 localhost
$
We can also exec in the container in an interactive mode by using the options
-i (interactive session) and
-t (pseudo-TTY):
$ docker container exec -it 8799a7ae86f4 /bin/bash
root@8799a7ae86f4:/# exit
exit
$