Docker is making it easy to build, deploy, and manage applications at scale. By using containers, Docker provides a lightweight, portable way to package applications along with their dependencies and configurations. In this tutorial, we will learn the fundamentals of creating Docker containers.

What is Docker?

Docker is an open-source platform that automates the deployment of applications inside lightweight and portable containers. It eliminates the it works on my machine problem by standardizing the environment in which applications run, making them independent of the underlying system.

Prerequisites

  • Docker installed on your local machine

Setting Up the Docker Environment

Before creating containers, ensure Docker is correctly installed and running:

docker --version

This command returns the Docker version, confirming its installation.

Creating a Dockerfile

A Dockerfile is a text document containing commands used to assemble a Docker image. Before we can create a Dockerfile, we need to create the directory for our Docker project.

mkdir docker_project
cd docker_project

Create a Dockerfile

touch Dockerfile

Edit the Dockerfile

# use an existing image as a base 
FROM python:3.8-slim 

# set the working directory in the container 
WORKDIR /app 

# Copy the dependencies file to the working directory
COPY requirements.txt .

# Install any dependencies 
RUN pip install –no-cache-dir -r requirements.txt 

# Copy the content of the local src directory to the working directory 
COPY src/ . 

# Command to run on container start 
CMD [“python”, “./python_script.py”]

Create a requirements.txt file

List the Python dependencies your application requires, and add your application source code to the src directory.

Building the Docker Image

With the Dockerfile in place, build the image:

docker build -t my_python_app .

This command builds an image from the Dockerfile in the current directory, tagging it as my_python_app.

Running a Container

Once the image is built, run a container from it:

docker run -d -p 5000:5000 my_python_app

This command runs the container in detached mode (-d), mapping port 5000 of the host to port 5000 in the container.

Managing Docker Containers

  • List running Containers
docker ps
  • Stop a Container:
docker stop [CONTAINER_ID]
  • Remove a Container:
docker rm [CONTAINER_ID]

Conclusion

Docker containers offer an efficient and standardized way for application deployment. By following the steps outlined in this tutorial, you can start using Docker for your development and deployment processes.

Now that you know the basics, try integrating Docker with CTO.ai to elevate your CI/CD pipeline, ensuring a uniform and secure environment for the seamless development, testing, and deployment of applications.

Ready to unlock the power of CTO.ai for your team? Schedule your consultation now with one of our experts today!