How to Create a Docker Container in 2024 to Efficiently Manage Docker Image Compartments

If you’re working on an application or a service that runs on multiple operating systems, Docker can simplify its deployment process.

With Docker container creation, you can effortlessly launch multiple applications or services on systems like virtual private server hosting or dedicated machines. Docker is also lightweight, easier to deploy, and offers better performance than virtual machines.

Docker containers have all the necessary dependencies to run applications, eliminating compatibility issues. Creating Docker containers from scratch is vital for any development project deployed using this open-source software.

This tutorial will guide you through creating a Docker container, detailing its benefits in software development and key best practices.

Download free docker cheat sheet

A Docker container is a self-contained software package with all the necessary dependencies to run a specific application on different operating systems. The Docker image dictates all the configuration instructions for starting or stopping containers. A new container is created whenever a user runs an image.

Why Use Docker Containers?

Docker containers are a game-changer for today’s developers. With container isolation, your apps can run on the same operating system while staying separate from other operating systems and containers. This feature ensures consistent performance in development and staging environments.

For businesses, Docker containers enhance deployment speed and maximize system resource utilization. Resource-wise, Docker container deployment requires significantly less memory than a virtual machine. Furthermore, their portable nature makes migrating and scaling legacy applications possible.

To summarize, Docker containers optimize the development process, saving valuable time and contributing to the cost-effective success of your application development projects.

How to Create a Docker Container

In this tutorial, we will use a virtual private server (VPS) with an Ubuntu 22.04 operating system. First, ensure that Docker is installed on your server. If it isn’t, follow our guide to install Docker on Ubuntu.

For Hostinger’s VPS customers, you can take advantage of our Ubuntu 22.04 64-bit with Docker template for automatic Docker installation. To use this template, log in to your VPS dashboard, then navigate to OS & Panel → Operating System.

Under the Applications drop-down menu, choose Ubuntu 22.04 64bit with Docker and click Change OS. Wait for the installation process to complete.

Selecting the Ubuntu 22.04 with Docker template on the VPS dashboard

To learn more about this template and how it stands out among others, read our dedicated Docker VPS hosting page.

Once the installation is done, follow these Docker containerization steps to run your application within an isolated environment.

1. Build a Docker Image

A Docker image is a blueprint for your container. It holds all the code, libraries, and dependencies your application needs to run.

When executing a Docker image, which can be privately owned or publicly shared on platforms like Docker Hub, it transforms into a Docker container.

While creating a new Docker image is possible, it is more practical to use a base image and build off of it since Docker Hub provides numerous base images that are readily available.

First, log in to your VPS using an SSH client like PuTTY. Then, use this Linux command to list all Docker images on your system:

sudo docker images

For more information on existing Docker images, use the following command:

sudo docker images --help

Use the -q option via the command prompt to list the numeric IDs of images available on your system:

sudo docker images -q

To list all non-dangling images that aren’t tagged or referenced by a new container, use this command:

sudo docker images -f dangling=false

For this tutorial, we will pull an image based on MySQL. Note that you can visit each image’s page for additional information.

Docker official image based on MySQL.

Import the new image to the current directory by executing the following command. Remember to replace <image name or image id> with your chosen image’s name or ID:

docker pull <image name or image id>
Installing Docker via SSH client.

Another alternative for creating a Docker image is to use Easypanel. This tool provides a graphical user interface to simplify the management of Docker images, especially for those not familiar with command-line operations.

EasyPanel facilitates the creation of Docker images for applications written in various programming languages like Node.js, Ruby, Python, PHP, Go, and Java. It automates many of the processes involved in setting up environments and dependencies.

Hostinger’s VPS hosting plans offer an Ubuntu 22.04 64bit with EasyPanel template, which can be installed through the same Operating System menu on your VPS dashboard.

It is your choice to use either a Docker-based or an EasyPanel-installed template. Select the one that fits your expertise and project requirements, whether it’s Docker for more control or EasyPanel for ease of use.

2. Write a Dockerfile

A Dockerfile is a text file that tells Docker how to build your image. It lists all the Docker commands needed to assemble a container image. Using a Dockerfile ensures your images are built the same way every time, making your work more consistent and easier to manage.

Here’s an example of a simple Dockerfile template:

FROM ubuntu:latest
WORKDIR /app
COPY . .
RUN apt-get update && apt-get install -y curl
CMD ["curl", "https://www.example.com"]

In a Dockerfile, each command creates a new layer in the Docker image. Here’s how it works, as shown in our example:

  • FROM ubuntu:latest ‒ this command pulls the latest Ubuntu parent image and sets it as the base layer. The following layers will be built on top of it.
  • WORKDIR /app ‒ sets the container’s working directory, creating a new layer that serves as the context for subsequent commands.
  • COPY . . ‒ copies local files into the same folder as the container, creating an additional layer containing your project files.
  • RUN apt-get update && apt-get install -y curl ‒ the Docker run command installs cURL in the container, adding a new layer for the updated package list and the installed cURL package.
  • CMD [“curl”, “https://www.domain.com”] ‒ sets the default command to run the application when the container starts.

Any changes you make while the container is running, like adding or modifying files, are written to the respective writable layers. This way, you can make temporary adjustments without affecting the base image.

Pro Tip

A Dockerfile is optional when using pre-built images from Docker Hub. However, it’s necessary for customizing or extending them.

3. Build the Docker Container

If you prepare a new Dockerfile, navigate to the same directory as said file and run the Docker build command to start a new image build process. Remember to replace the <image name or image id> option with your tag name.

docker build -t <image name or image id>

Starts a new container from the image you just built using the Docker run command:

docker run <image name or image id>

Otherwise, run a pre-built image imported from Docker Hub. Let’s use the MySQL image that we pulled previously:

docker run mysql
Building a container based on an existing image.

Efficient image layering is crucial for optimizing build time and resource usage. Each command in a Dockerfile creates a new layer, which Docker caches. When you rebuild an image, Docker reuses unchanged layers, speeding up the build process.

Moreover, efficient layering can reduce the image size, making it quicker to pull, push, or deploy. This practice is particularly vital for businesses needing fast deployments to stay competitive.

4. Run and Manage Containers

Once we create the container image, start one using the Docker run command. Replace <container name> with your chosen name. Here, mysql bash represents which container we’ll be running.

docker run --name <container name> -it mysql bash

Use the Docker ps command with the -a option to list your system’s running containers. Add sudo at the start of the command to execute it with root permissions.

docker ps -a

Use the following Docker command to see the top process of a container:

docker top MyContainer
Docker top command displays the top process of a running container.

To map ports between the host and the container, use the -p option alongside the docker run command:

docker run -p host_port:container_port <image name>

Mapping ports expose your container’s application to the outside, allowing access from your host machine. This process is vital for web servers, databases, or any application that connects with external systems.

To attach a volume for persistent storage, use the -v option:

docker run -v host_directory:container_directory <image name>

Attaching volumes makes your container setup more robust, easier to manage, and perform better. Your data remains intact even if the Docker container setup is stopped, deleted, or updated. Furthermore, volumes can be shared between various containers, simplifying managing data in multi-container setups.

Pro Tip

Use Docker CLI commands or the Docker API to manage volumes.

You can limit resources like CPU and memory by using –cpus and –memory options. The following example limits the container to up to 0.5 CPUs and 500 MB of RAM.

docker run --cpus=0.5 --memory=500m <image name>

Issue the following command to stop the running container:

docker stop MyContainer

The following command showcases the container’s additional information, including container ID, CPU utilization, and memory usage:

docker stats
Container's information shown using the docker stats command.

To terminate the Docker container, enter the following command on the command line:

docker kill MyContainer

Docker Container Best Practices

Here are some best practices to ensure an efficient Docker containerization process.

Use Kodee

Efficiency is vital when creating Docker containers. Fortunately, Hostinger customers can use the Kodee AI assistant to simplify VPS management tasks, from providing installation guides to recommending appropriate commands.

This feature is accessible from the left panel on your VPS dashboard. You can enter queries about the Docker containerization process, such as “How to dynamically update the container when the base image changes?”

Kodee will respond with a comprehensive answer, including any relevant commands or scripts.

Suggested Reading

Learn how to use Kodee with our curated list of top AI prompts for efficient VPS management.

Keep Containers Lightweight

Smaller containers are faster, more efficient, and more secure. They deploy quickly, use fewer resources, and maximize hardware utilization. With fewer components, they reduce the attack surface, improving overall security.

Follow these tips to create lightweight containers:

  • Opt for light base images ‒ if you have multiple similar images, build a base image with shared components and create custom Docker images from it.
  • Use multi-stage builds ‒ include only essential components like artifacts and environment in the final image.
  • Remove unnecessary files ‒ after installing packages, optimize your Docker application’s performance by removing unused Docker images, cache, and temporary files.
  • Be specific in commands ‒ consolidate commands into a single run line to reduce image layers. Additionally, avoid installing recommended or suggested packages that aren’t essential.

Use Official Images

Using official images from Docker Hub for Docker image building guarantees a secure, optimized, and reliable foundation for your containers. They are often tailored for specific use cases, providing an efficient starting point for developing robust and efficient applications.

Security-wise, official images undergo thorough security checks and are promptly patched for vulnerabilities. Since they’re widely used, official images are well-tested and compatible with various configurations and platforms.

Limit Container Permissions

Running containers with extra privileges poses a security risk. A hacker can gain complete control of your system if a container is breached while running as root.

To maintain system security, only grant necessary permissions to your container. Create and use a non-root user for running your application inside the container. You can also set your container to read-only mode to prevent unwanted changes.

Secure Sensitive Information

When the Docker container starts, you can configure environment variables depending on the application or service running inside it. Some of the most common variables include database credentials, application settings, and secret values for authentication.

Environment variables keep sensitive data separate from your code and image, hiding it from ones with access to both. Using environment variables also makes your setup more flexible, as you can easily change the data without altering the Dockerfile or rebuilding the image.

Leverage Container Orchestration

Container orchestration tools like Docker Compose and Kubernetes simplify managing multi-container applications. They streamline deployment by letting you launch several containers with a single command.

For example, you can use Docker Compose to install WordPress with all the necessary components, like a web server and a database.

Orchestration tools also handle scaling, automatically adjusting services as traffic grows. They distribute incoming network traffic across several containers, improving performance and reliability.

Conclusion

Docker is an invaluable tool for today’s developers and businesses, offering a consistent environment, streamlined deployments, and optimized resource utilization. Knowing how to build one helps make your development cycle more efficient and secure.

We covered the steps to create a Docker container from an image and common Docker commands to complete the process. You also learned the best practices for efficient Docker container management on the Ubuntu 22.04 virtual private server.

If you have any questions about creating Docker containers, leave a comment below.

How to Create a Docker Container FAQ

This section covers frequently asked questions about creating Docker containers.

What Is a Docker Image vs Container?

A Docker image is a blueprint for creating a container, holding the application’s code, libraries, and dependencies. On the other hand, a Docker container is a running version of an image. When you start a container from an image, the system creates a live environment where the application can run and interact.

Can a Docker Image Have Multiple Containers?

Yes, you can use a single Docker image to create several containers. Each container runs independently and has its own set of resources and settings. This practice allows you to scale or run applications in various environments without creating a Docker image each time, saving time and resources.

Can Docker Images Be Edited?

Docker images are made of read-only layers, so you can’t edit them directly. To make changes, update the Dockerfile or source files and build a new image with the Docker build command. As existing containers won’t update automatically, you must stop them and make new ones from the image created.

Author
The author

Jordana Alexandrea

Jordana is a Senior Content Writer with over 5 years of experience in digital marketing and web development. When she’s not busy with work, she dabbles in creative writing and movie reviewing. Follow her on LinkedIn.