Limited time offer! 25% off our lifetime plans with code LMT25 at checkout. View plans →

DevOps

Docker Container Deployment: Step-by-Step Guide for Beginners

DOCKER CONTAINER DEPLOYMENT
On this page

Docker container deployment is the process of running an application inside a Docker container so it can operate in a consistent, isolated environment. It involves preparing an application image, configuring its ports and storage, starting the container, and checking that the application works correctly. You can deploy a single container with Docker commands or manage a complete application stack with Docker Compose.

This guide explains how to deploy a Docker container on a Linux server, configure it for ongoing use, and troubleshoot common deployment problems.

What Is Docker Container Deployment?

Docker container deployment makes an application available by running it inside a container created from a Docker image. The image contains the application and its required files, while the container provides the runtime environment.

For example, you can deploy an NGINX web server inside a container without manually installing NGINX and configuring its dependencies directly on the host operating system.

Docker container deployment typically involves these components:

ComponentPurpose
Docker imagePackages the application and its runtime requirements
Docker containerRuns an instance of an image
DockerfileDefines how to build a custom image
Port mappingMakes a container service accessible through the host
Docker volumeStores data that must persist beyond a container’s lifecycle
Docker ComposeDefines and manages applications with multiple services
Container registryStores images so they can be downloaded by deployment servers

These components work together to make application deployment more repeatable across development, testing, and production environments.

Prerequisites for Docker Container Deployment

Before deploying a container, prepare the server and verify that Docker is available.

You will need:

  • A Linux server or a local machine with Docker installed.
  • SSH access if you are deploying to a remote server.
  • Sufficient CPU, RAM, and disk space for the application.
  • A Docker image from a trusted registry or a project containing a Dockerfile.
  • Open network ports required by the application.
  • Appropriate permissions to run Docker commands.

If Docker is not installed, follow the official Docker Engine installation guide for your Linux distribution.

After installation, check the Docker version:

docker --version

Check whether the Docker service is running on a Linux server that uses systemd:

sudo systemctl status docker

If the service is stopped, start it:

sudo systemctl start docker

You can also configure Docker to start automatically when the server boots:

sudo systemctl enable docker

Verify that Docker can run a test container:

sudo docker run hello-world

If the command completes successfully, Docker can download and run an image.

How to Deploy a Docker Container

The simplest way to understand Docker container deployment is to run an existing image. The following example deploys an NGINX web server on a Linux machine.

Step 1: Download the Docker Image

Docker images contain the files and instructions required to start an application. You can download a published image from a container registry.

Run:

sudo docker pull nginx:alpine

This command downloads the Alpine-based NGINX image if it is not already available locally.

You can confirm that the image exists:

sudo docker images

The output lists the available images, their tags, and their sizes.

Step 2: Create and Run the Container

Once the image is available, start a container:

sudo docker run -d \
  --name web-server \
  --publish 8080:80 \
  --restart unless-stopped \
  nginx:alpine

This command creates and starts a container named web-server.

Here is what each option does:

OptionExplanation
-dRuns the container in the background
--name web-serverAssigns a readable name to the container
--publish 8080:80Maps host port 8080 to container port 80
--restart unless-stoppedRestarts the container automatically unless it was deliberately stopped
nginx:alpineSpecifies the image used to create the container

The port mapping means that requests to port 8080 on the host are forwarded to port 80 inside the container.

Step 3: Verify the Deployment

Check whether the container is running:

sudo docker ps

You should see web-server in the list of running containers.

Next, test the web server from the machine running Docker:

curl http://localhost:8080

NGINX should return an HTML response.

If you are accessing a remote server, open the following address in your browser:

http://SERVER_IP:8080

Replace SERVER_IP with your server’s actual IP address.

Ensure that the firewall and any cloud security rules permit the required traffic. For a public production website, exposing an application through a reverse proxy with HTTPS is generally preferable to leaving an application port directly accessible.

Step 4: Review Container Logs

If the application does not respond, inspect its logs:

sudo docker logs web-server

To follow new log entries as they appear, use:

sudo docker logs -f web-server

Press Ctrl+C to stop following the logs. This does not stop the container.

Step 5: Stop, Start, or Remove the Container

Docker provides commands for managing a deployed container.

sudo docker stop web-server

This stops the running container.

Start it again with:

sudo docker start web-server

To restart it:

sudo docker restart web-server

If you no longer need the container, stop and remove it:

sudo docker stop web-server
sudo docker rm web-server

Removing a container does not automatically remove the image. Named volumes may also remain, depending on how they were created and mounted.

How to Deploy Your Own Application with Docker

Running a published image is useful for testing, but many projects require a custom image built from application source code.

For this example, assume you have a simple Python application in a directory named my-app.

The directory contains two files:

my-app/
├── app.py
└── Dockerfile

The Python application will use port 8000.

Step 1: Create the Application

Create app.py with the following code:

from http.server import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/plain")
        self.end_headers()
        self.wfile.write(b"Docker deployment is working!")

server = HTTPServer(("0.0.0.0", 8000), Handler)
server.serve_forever()

This basic HTTP server returns a message when a client sends a request. It is intended for learning, not as a production application server.

Step 2: Create a Dockerfile

Inside the same directory, create a file named Dockerfile:

FROM python:3.12-slim

WORKDIR /app

COPY app.py .

EXPOSE 8000

CMD ["python", "app.py"]

The instructions define how Docker builds the application image.

  • FROM selects a base image with Python installed.
  • WORKDIR sets the working directory inside the image.
  • COPY adds the application file.
  • EXPOSE documents the port used by the application.
  • CMD defines the default command that runs when the container starts.

The EXPOSE instruction does not publish the port to the host. You must configure port mapping when starting the container.

Step 3: Build the Docker Image

Open a terminal in the my-app directory and run:

sudo docker build -t my-python-app:1.0 .

The -t option assigns a name and tag to the image. The final dot specifies the current directory as the build context.

Check that Docker created the image:

sudo docker images

You should find my-python-app with the tag 1.0.

Step 4: Run the Application Container

Start a container from the image:

sudo docker run -d \
  --name python-app \
  --publish 127.0.0.1:8000:8000 \
  --restart unless-stopped \
  my-python-app:1.0

This maps port 8000 inside the container to port 8000 on the host’s loopback interface. Binding to 127.0.0.1 means the application port is accessible only from the host itself, rather than directly from external network interfaces.

Test it on the server:

curl http://127.0.0.1:8000

Expected response:

Docker deployment is working!

If the test succeeds, the custom application has been built and deployed successfully.

For a public deployment, place the application behind a properly configured reverse proxy or another suitable ingress layer. Avoid binding the application directly to a public interface unless that exposure is intentional and protected.

How to Deploy Multiple Containers with Docker Compose

A real application may require several services, such as a web application, an API, and a database. Starting each container separately can make configuration and maintenance harder.

Docker Compose lets you define services in a compose.yaml file and manage them together.

For example, consider an application that needs a web server and a Redis service.

Create a directory for the project and add this file:

services:
  web:
    image: nginx:alpine
    ports:
      - "127.0.0.1:8080:80"
    restart: unless-stopped

  redis:
    image: redis:7-alpine
    restart: unless-stopped

This configuration defines two services. Docker Compose creates and manages a separate container for each service and connects them to a shared project network.

The web service is available on the host at 127.0.0.1:8080. The Redis service is not directly published to the host, but the web service can reach it using the service name redis on the Compose network.

Start the application stack:

sudo docker compose up -d

Check its status:

sudo docker compose ps

View the service logs:

sudo docker compose logs

To stop and remove the containers and network created for the project, run:

sudo docker compose down

This example demonstrates service orchestration only. It does not configure an application to use Redis, and the Redis configuration shown is not a complete production security setup. Before deploying a real application, configure its environment variables, secrets, storage, health checks, and service dependencies as required.

For more information, see the official Docker Compose documentation.

How to Deploy Docker Containers on a VPS

A virtual private server (VPS) provides a dedicated virtual environment where you can install Docker and run containerized applications.

A typical Docker container deployment on a VPS follows this workflow:

  1. Provision a VPS with enough CPU, RAM, and disk space for your application.
  2. Install a supported Linux distribution and apply system updates.
  3. Install Docker Engine and verify that the service is running.
  4. Connect to the VPS over SSH.
  5. Pull an existing image or build an image from your application’s Dockerfile.
  6. Configure port mappings, environment variables, networks, and persistent storage.
  7. Start the container with an appropriate restart policy.
  8. Test the application and monitor its logs and resource usage.
  9. Configure DNS, HTTPS, backups, and firewall rules before exposing it publicly.

A VPS is particularly useful when you need control over the operating system, container runtime, networking, and deployment configuration.

If you are choosing a server for containerized applications, consider available memory, CPU allocation, storage performance, network capacity, and backup options. You can explore CyberPanel Cloud VPS for VPS hosting options.

Keep in mind that CyberPanel and Docker serve different purposes. CyberPanel is a web hosting control panel, while Docker manages containers. A Docker deployment may coexist with a web hosting stack, but port conflicts, reverse proxy configuration, firewall rules, and resource allocation must be planned carefully.

Docker Container Deployment Best Practices

A container that starts successfully is not automatically ready for production. Use the following practices to improve reliability, security, and maintainability.

Use Specific Image Tags

Avoid relying on the latest tag for important production deployments. Use a specific version or an immutable image digest when you need more predictable deployments.

For example:

docker pull nginx:1.28-alpine

Before using a version in production, confirm that it is supported and appropriate for your application. Update pinned versions through a tested release process.

Configure Persistent Storage

A container’s writable layer is not a substitute for durable application storage. Data stored only inside a container may be lost when the container is removed.

For example, create a named volume:

docker volume create app-data

Mount it into a container:

docker run -d \
  --name data-example \
  --mount source=app-data,target=/data \
  busybox:stable \
  sh -c "while true; do sleep 3600; done"

The volume persists independently of the container’s writable layer. However, persistence is not the same as a backup. Create and test backups for important data.

Protect Secrets and Credentials

Do not hardcode database passwords, API keys, or other secrets into a Dockerfile or commit them to source control.

Use an appropriate secrets-management approach for your environment. Restrict access to deployment files and environment configuration, and avoid exposing sensitive values in logs.

Limit Container Privileges

Run applications as non-root users inside containers when supported. Avoid using privileged containers unless there is a clear operational requirement.

Publish only the ports that must be accessible, restrict unnecessary network access, and use trusted images. Keep the Docker Engine and host operating system updated.

Remember that membership in the Docker group can grant root-equivalent control over a Linux host. Treat access to Docker as a privileged permission.

Configure Restart Policies and Health Checks

A restart policy helps Docker restart a container after certain stops or failures. For example:

docker run -d \
  --name my-service \
  --restart unless-stopped \
  nginx:alpine

Restart policies do not prove that an application is healthy. For production services, configure an appropriate health check and monitoring system as well.

Monitor Resources and Logs

Use these commands to inspect running containers and resource consumption:

docker ps
docker stats
docker logs my-service

Monitor CPU, memory, disk usage, and application response times. Set suitable resource limits when needed, based on workload testing and the host’s capacity.

Plan Image Updates and Rollbacks

Do not treat rebuilding an image as a complete deployment strategy. Test new images before replacing a working version, keep deployment configuration under version control, and prepare a rollback plan.

For stateful applications, coordinate application updates with database migrations and backups.

Common Docker Container Deployment Problems

The following table covers frequent issues and the checks that can help identify their causes.

ProblemPossible causeWhat to check
Container exits immediatelyApplication error or incorrect startup commandRun docker logs CONTAINER_NAME
Port is unavailableAnother service uses the host portCheck docker ps and host listening ports
Application cannot be reachedIncorrect port mapping or firewall rulesVerify published ports and firewall configuration
Image pull failsIncorrect image name, tag, or registry accessCheck the image reference and registry credentials
Data disappearsData was stored only in the container’s writable layerConfigure a volume or suitable bind mount
Container keeps restartingApplication crashes or required configuration is missingInspect logs, exit status, and environment settings
Permission deniedIncorrect ownership, file permissions, or security policyCheck the mounted paths and the container’s user
Application cannot reach another serviceIncorrect network or service configurationCheck network membership and service names

Check Why a Container Stopped

List all containers, including stopped ones:

docker ps -a

Inspect the container’s configuration and exit status:

docker inspect CONTAINER_NAME

Read its logs:

docker logs CONTAINER_NAME

These checks can help distinguish application errors from port, permission, or configuration problems.

Check Port Mappings

Run:

docker port CONTAINER_NAME

This shows the published port mappings for the container. Compare them with the port on which the application actually listens inside the container.

If a port is already in use on the host, select another host port or resolve the conflicting service before redeploying.

Docker Container Deployment vs. Virtual Machines

Docker containers and virtual machines both help run applications in isolated environments, but they use different approaches.

FeatureDocker containersVirtual machines
Operating systemShare the host kernelTypically run a separate guest operating system
Resource overheadOften lower for comparable workloadsOften higher because each VM runs its own OS
StartupUsually fast, depending on the applicationDepends on guest OS and workload
IsolationProcess and resource isolation, dependent on configurationHardware-virtualization boundary with a separate guest OS
PortabilityImages help standardize application environmentsVM images package a complete virtual machine
Best suited forApplication packaging and repeatable deploymentWorkloads needing separate guest OS environments or stronger architectural separation

Neither approach is universally better. Choose based on security requirements, operating system needs, performance, operational complexity, and application architecture.

Frequently Asked Questions

How do I deploy a Docker container?

Install Docker, pull or build an image, and start a container using docker run. Configure the required ports, storage, environment variables, and restart policy, then verify the application with logs and a suitable test request.

Can I deploy Docker containers on a VPS?

Yes. You can install Docker Engine on a supported VPS operating system and run containers there. Ensure that the server has enough resources and that its firewall, network ports, storage, and security settings match the application’s requirements.

Is Docker Compose required for container deployment?

No. You can deploy a single container with docker run. Docker Compose is useful when an application has multiple services or when you want to keep deployment configuration in a file.

Does removing a Docker container delete its data?

Not necessarily. Removing a container removes its writable layer, but separately managed named volumes generally remain unless they are explicitly removed. Bind-mounted files remain on the host. Always verify where application data is stored and maintain backups.

Is Docker container deployment suitable for production?

Yes, Docker is widely used for production deployments. A production setup also needs secure image management, access controls, persistent storage, monitoring, tested updates, backups, and a recovery plan.

Conclusion

Docker container deployment provides a repeatable way to run applications across development machines and servers. Start by deploying a trusted image, verify port mappings and logs, and then build custom images or use Docker Compose as your requirements grow.

For production workloads, prioritize persistent storage, least-privilege access, reliable monitoring, and a tested update and rollback process. These practices help make containerized applications easier to maintain and safer to operate.

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat on WhatsApp