Python > Deployment and Distribution > Containerization > Building Docker Images
Building a Docker Image and Running a Container
This snippet shows the commands to build a Docker image from a Dockerfile and then run a container based on that image.
Building the Docker Image
This command builds a Docker image. Let's break it down:
Before running this, make sure you are in the same directory as your Dockerfile.
docker build -t my-python-app .
Running the Docker Container
This command runs a container based on the Docker image we just built. Here's the breakdown:
docker run -d -p 5000:5000 my-python-app
Accessing the Application
After running the container with the above command, you should be able to access your application by opening a web browser and navigating to `http://localhost:5000`. This assumes that your Python application is a web application that listens on port 5000 inside the container and that you have correctly mapped the ports using the `-p` flag in the `docker run` command.
Checking Container Logs
To view the logs of a running container, you can use the `docker logs` command followed by the container ID. You can obtain the container ID by running `docker ps`.
docker logs <container_id>
Real-Life Use Case
This is a fundamental step in deploying any containerized application. You build the image once based on your application and its dependencies, and then you can run multiple containers from that image, scaling your application as needed.
Best Practices
Interview Tip
Understand the entire Docker workflow, from writing a Dockerfile to building an image, running a container, and managing images and containers. Be able to troubleshoot common Docker issues.
When to use them
Use these commands whenever you need to create and run Docker containers. This is a core part of any containerized application deployment process.
Memory Footprint
The memory footprint of the container will depend on the resources used by the application running inside the container. You can limit the memory usage of a container using the `--memory` flag in the `docker run` command.
Alternatives
Alternatives for running containers include Kubernetes, Docker Swarm, and other container orchestration platforms.
Pros
Cons
FAQ
-
How do I stop a running container?
You can stop a running container using the command `docker stop`. You can obtain the container ID by running `docker ps`. -
How do I remove a Docker image?
You can remove a Docker image using the command `docker rmi`. You can obtain the image ID by running `docker images`.