To drop into the /bin/sh (or /bin/bash, depending on the image) of a Docker container instead of running the default command specified in the image, you can override the container's default entrypoint or command when starting it. Here's how you can achieve this:
1. Using docker run with an Interactive Shell
You can start a container and override its default behavior by specifying /bin/sh (or /bin/bash) as the command to run. Use the -it flags to allocate a pseudo-TTY and keep the session interactive.
docker run -it --entrypoint /bin/sh <image_name>
-i: Keeps the session interactive.
-t: Allocates a pseudo-TTY.
--entrypoint /bin/sh: Overrides the default entrypoint of the image to start a shell (/bin/sh).
If the image uses /bin/bash instead of /bin/sh, replace /bin/sh with /bin/bash.
2. Using docker run Without --entrypoint
If the image does not have a strict entrypoint but specifies a default command, you can simply append /bin/sh (or /bin/bash) to the docker run command:
docker run -it <image_name> /bin/sh
This approach works if the image's CMD is not set to enforce a specific behavior.
3. Dropping into a Running Container
If the container is already running and you want to access its shell, you can use the docker exec command:
docker exec -it <container_id_or_name> /bin/sh
<container_id_or_name>: The ID or name of the running container.
/bin/sh: Starts a shell session inside the container.
Again, replace /bin/sh with /bin/bash if the image supports it.
4. Handling Images Without /bin/sh
Some minimal Docker images (e.g., scratch or distroless) may not include /bin/sh. In such cases:
- Check the image documentation for alternative debugging methods.
- Use a more feature-rich base image for debugging purposes.
5. Example Walkthrough
Suppose you have an image named myapp:latest and want to inspect its filesystem or debug its environment.
Start a Shell Instead of Running the Default Command:
docker run -it --entrypoint /bin/sh myapp:latest
Access a Running Container:
First, find the container ID or name:
docker ps
Then, drop into the shell:
docker exec -it <container_id_or_name> /bin/sh
Notes:
- If the image does not include
/bin/sh or /bin/bash, you may need to modify the Dockerfile to include these tools or use a different debugging approach.
- Always ensure you are using the correct shell path (
/bin/sh, /bin/bash, etc.) based on the image's configuration.
By following these steps, you can effectively drop into the shell of a Docker container or image for inspection and debugging.