Executing Commands in a Docker Container
Docker containers are isolated environments that allow you to run applications and services in a consistent, reproducible, and portable way. To execute commands within a Docker container, you can use the following methods:
1. docker exec
Command
The docker exec
command allows you to execute a command in a running Docker container. This is the most common way to interact with a running container.
Here's the basic syntax:
docker exec [options] <container_id|container_name> <command>
For example, to run the ls
command in a running container named "my-container":
docker exec my-container ls
You can also use the docker exec
command to start an interactive shell within the container:
docker exec -it my-container /bin/bash
The -i
(interactive) and -t
(tty) options are used to create an interactive terminal session.
2. docker run
Command
The docker run
command can be used to execute a command in a new container. This is useful when you want to perform a one-time task or test something in a fresh container environment.
Here's the basic syntax:
docker run [options] <image> <command>
For example, to run the ls
command in a new container based on the "ubuntu" image:
docker run ubuntu ls
You can also run an interactive shell in a new container:
docker run -it ubuntu /bin/bash
3. Dockerfile CMD
and ENTRYPOINT
Instructions
In a Dockerfile, you can specify the default command to be executed when a container is started using the CMD
instruction. This allows you to define the primary process that will run in the container.
Here's an example Dockerfile:
FROM ubuntu
CMD ["echo", "Hello, Docker!"]
When you run a container based on this image, the echo "Hello, Docker!"
command will be executed:
docker run my-image
The ENTRYPOINT
instruction in a Dockerfile can be used to set the default command for the container, with the ability to pass additional arguments when the container is run.
Here's an example Dockerfile with an ENTRYPOINT
:
FROM ubuntu
ENTRYPOINT ["echo"]
CMD ["Hello, Docker!"]
When you run a container based on this image, the echo
command will be executed with the argument "Hello, Docker!":
docker run my-image
docker run my-image "Goodbye, Docker!"
In the second example, the "Goodbye, Docker!" argument will be passed to the echo
command.
Mermaid Diagram: Executing Commands in a Docker Container
This diagram illustrates the three main ways to execute commands in a Docker container: using the docker exec
command, the docker run
command, and the CMD
and ENTRYPOINT
instructions in a Dockerfile.
In summary, the docker exec
command allows you to execute commands in a running container, the docker run
command can be used to run a command in a new container, and the Dockerfile instructions CMD
and ENTRYPOINT
define the default command and entry point for a container, respectively.