Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Managing Docker Containers

Introduction

Docker containers are lightweight, standalone, and executable packages that include everything needed to run a piece of software, including the code, runtime, libraries, and dependencies. This tutorial will guide you through the process of managing Docker containers, from creating and running containers to stopping and removing them.

Prerequisites

Before you start, ensure you have Docker installed on your machine. You can download Docker from the official Docker website.

Creating a Docker Container

To create a Docker container, you need to have a Docker image. You can either build your own image or pull one from the Docker Hub. Here, we will pull an image of Nginx from Docker Hub.

docker pull nginx

This command pulls the latest Nginx image from Docker Hub.

Running a Docker Container

Once you have the image, you can run a container using the following command:

docker run -d -p 8080:80 --name mynginx nginx

This command does the following:

  • -d runs the container in detached mode.
  • -p 8080:80 maps port 8080 on your host to port 80 in the container.
  • --name mynginx names the container "mynginx".
  • nginx specifies the image to use.

Listing Docker Containers

To list running containers, use the following command:

docker ps

CONTAINER ID   IMAGE     COMMAND                  CREATED        STATUS        PORTS                  NAMES
abc123def456   nginx     "nginx -g 'daemon of…"   2 minutes ago   Up 2 minutes  0.0.0.0:8080->80/tcp   mynginx
                

To list all containers, including stopped ones, use:

docker ps -a

Stopping a Docker Container

To stop a running container, use the following command:

docker stop mynginx

This command stops the "mynginx" container.

Removing a Docker Container

To remove a stopped container, use the following command:

docker rm mynginx

This command removes the "mynginx" container. Make sure the container is stopped before attempting to remove it.

Viewing Container Logs

To view logs from a container, use the following command:

docker logs mynginx

This command shows the logs for the "mynginx" container.

Executing Commands in a Running Container

You can execute commands in a running container using the following command:

docker exec -it mynginx /bin/bash

This command opens an interactive terminal in the "mynginx" container.

Conclusion

Managing Docker containers involves creating, running, stopping, and removing containers, as well as viewing logs and executing commands within them. By mastering these commands, you can effectively manage your Docker containers and ensure your applications run smoothly.