Running Docker Containers
Once you have created a Docker image, the next step is to run it as a container. Docker provides a simple and efficient way to run containers on your local machine or in a production environment.
Running a Docker Container
To run a Docker container, you can use the docker run
command followed by the name or ID of the image you want to run. For example, if you have an image called myapp-image
, you can run it with the following command:
1docker run myapp-image
This command will start a new container based on the specified image.
Managing Docker Containers
Docker provides various commands to manage running containers.
- To list all running containers, you can use the
docker ps
command. - To stop a running container, you can use the
docker stop
command followed by the container ID or name. - To remove a stopped container, you can use the
docker rm
command followed by the container ID or name.
Controlling Container Resources
Docker allows you to control the resources allocated to a container, such as CPU and memory.
- To limit the CPU usage of a container, you can use the
--cpus
option followed by the number of CPUs you want to allocate. For example,--cpus 0.5
would limit the container to use only 50% of a single CPU. - To limit the memory usage of a container, you can use the
--memory
option followed by the amount of memory you want to allocate. For example,--memory 512m
would limit the container to use only 512 megabytes of memory.
Example: Running a Spring Boot Application
Let's say you have a Spring Boot application packaged as a JAR file. You can run it as a Docker container using the following command:
1# Build the Docker image
2docker build -t myapp-image .
3
4# Run the Docker container
5docker run -p 8080:8080 myapp-image
This command builds the Docker image using the Dockerfile located in the current directory (.
) and tags it as myapp-image
. Then it runs the container from the built image and maps port 8080
on the host to port 8080
inside the container.
Congratulations! You have learned how to run Docker containers and manage them effectively. In the next lesson, we will explore Docker networking and how to create networks for your containers.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// Replace with your Java logic here
System.out.println("Hello, Docker!");
}
}