After setting up Docker on your local system (Docker Desktop is available for Windows, MacOS, and Linux), you can proceed to create a Dockerfile. Dockerfile is a simple text file that contains all the commands needed to build a Docker image. It’s essentially the blueprint of your application, detailing its environment and listing its dependencies.
Here’s a basic example of a Dockerfile:
# Use an official Python runtime as a parent image
# Set the working directory in the container to /app
# Add the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt
# Make port 80 available to the world outside this container
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
This Dockerfile creates a Python 3.7 environment, sets up the necessary working directory, copies the necessary application files into the container, installs the necessary dependencies, exposes port 80 for the application, sets an environment variable, and finally, runs the application.
Building Docker Images
Once you have a Dockerfile, you can create a Docker image using the
docker build command. This command reads the Dockerfile, downloads the necessary parent image, and follows the instructions written in the Dockerfile to create a new image. You also provide a tag to your image using
docker build -t my-python-app:1.0 .
my-python-app is the name of the image and
1.0 is the version tag. The dot at the end signifies that Docker should look for the Dockerfile in the current directory.
Running Docker Containers
After creating the Docker image, you can start a container from that image using the
docker run command.
docker run -p 4000:80 my-python-app:1.0
In this command,
-p 4000:80 maps the host’s port 4000 to the container’s port 80. So, the application running inside the Docker container would be accessible on port 4000 of the host machine.
Sharing Docker Images
Docker provides a platform known as Docker Hub, which acts as a cloud-based registry service for sharing Docker images. You can push your locally created Docker images to Docker Hub using the
docker push command, which allows you to share your application with the world.
docker push my-python-app:1.0
In conclusion, Docker revolutionizes application development by providing a platform that ensures the consistency and reliability of an application from development to production. This not only saves time but also reduces the chances of encountering the “it works on my machine” problem. The use of Docker has become a standard practice in today’s DevOps culture, and it’s an essential tool for modern software developers.