Docker Container and Basic Commands

Docker Container

Docker containers are lightweight, standalone, and executable packages that include everything needed to run a piece of software, including the code, runtime, system tools, libraries, and settings. In this chapter, we’ll explore how to work with Docker containers effectively.

Running Your First Container

Let's start by running a simple container

docker run hello-world

This command does the following

1.  Checks for the hello-world image locally
2.  If not found, pulls the image from Docker Hub
3.  Creates a container from the image
4.  Runs the container, which prints a hello message
5.  Exits the container

Basic Docker Commands

Here are some essential Docker commands for working with containers

Listing Containers

To see all running containers

docker ps

To see all containers (including stopped ones)

docker ps -a

Starting and Stopping Containers

To stop a running container

docker stop <container_id or name>

To start a stopped container:

docker start <container_id_or_name>

To restart a container

docker restart <container_id_or_name>

Removing Containers

To remove a stopped container

docker rm <container_id_or_name>

To force remove a running container

docker rm -f <container_id_or_name>

Running Containers in Different Modes

Detached Mode

Run a container in the background

docker run -d <image_name>

Interactive Mode

Run a container and interact with it

docker run -it <image_name> /bin/bash

Port Mapping

To map a container's port to the host

docker run -p <host_port>:<container_port> <image_name>

Example:

docker run -d -p 80:80 nginx

Working with Container Logs

View container logs:

docker logs -f <container_id_or_name>

Executing Commands in Running Containers

To execute a command in a running container:
To execute a command in a running container:

docker exec -it <container_id_or_name> <command>

Example:

docker exec -it my_container /bin/bash

Remember, containers are designed to be ephemeral. Always store important data in volumes or use appropriate persistence mechanisms for your applications.

Chatbot