Docker Container Access
Overview
After running a Docker image, there are times when you need to enter the container to check or perform work.
This section introduces how to access a Docker container.
Run a Test Container
First, run a container for testing.
% docker run --name nginx-server -d -p 80:80 nginx
If there is already a running container, you can use that container instead.
Check the List of Running Containers
Check the list of currently running containers.
% docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7346db27830e nginx "/docker-entrypoint.…" 23 seconds ago Up 22 seconds 0.0.0.0:80->80/tcp nginx-server
Connect to the Container
Enter the CONTAINER ID or NAMES of the container you want to access, as confirmed above.
You can connect to the container by CONTAINER ID.
% docker exec -it 7346db27830e /bin/bash
root@7346db27830e:/#
Or you can connect by NAMES.
% docker exec -it nginx-server /bin/bash
root@7346db27830e:/#
The exec command is used to send a command inside a Docker container. When /bin/bash is passed as an argument, the bash shell inside the Docker container is executed.
Accessing a container ultimately means using a Linux shell, and this method lets you connect to the container.
Exit the Container
To exit the container, use the exit command.
% docker exec -it 7346db27830e /bin/bash
root@7346db27830e:/# exit
exit
Connect with /bin/sh
Sometimes a Docker image does not include the /bin/bash command. In that case, access may fail as shown below.
% docker exec -it 2910a51bdaf7 /bin/bash
OCI runtime exec failed: exec failed: unable to start container process: exec: "/bin/bash": stat /bin/bash: no such file or directory: unknown
In this case, try accessing the container with /bin/sh.
docker exec -it 285c3f2a0024 /bin/sh