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-imageThis 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 pscommand. - To stop a running container, you can use the
docker stopcommand followed by the container ID or name. - To remove a stopped container, you can use the
docker rmcommand 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
--cpusoption followed by the number of CPUs you want to allocate. For example,--cpus 0.5would limit the container to use only 50% of a single CPU. - To limit the memory usage of a container, you can use the
--memoryoption followed by the amount of memory you want to allocate. For example,--memory 512mwould 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-imageThis 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.
xxxxxxxxxxclass Main { public static void main(String[] args) { // Replace with your Java logic here System.out.println("Hello, Docker!"); }}


