Common Docker Commands
Basic Docker Commands
1. List Docker images
docker images
2. List running containers
docker ps
3. List all containers (including stopped ones)
docker ps -a
4. Start a container
docker start <container_id_or_name>
5. Stop a container
docker stop <container_id_or_name>
6. Remove a container
docker rm <container_id_or_name>
7. Remove an image
docker rmi <image_id_or_name>
8. Run a new container
docker run <image_name>
To run in detached mode
docker run -d <image_name>
Connecting host ports to containers.
docker run -p <host-port>:<container-port> <image>
9. Run a container with an interactive shell
docker run -it <image_name> /bin/bash
10. Stop all running containers
docker stop $(docker ps -q)
Building and Managing Images
1. Build an image from a Dockerfile
docker build -t <image_name> .
2. Tag an image
docker tag <image_id_or_name> <new_image_name:tag>
3. Push an image to a repository
docker push <image_name:tag>
4. Pull an image from a repository
docker pull <image_name:tag>
Working with Volumes and Networks
1. Create a volume
docker volume create <volume_name>
2. List all volumes
docker volume ls
3. Remove a volume
docker volume rm <volume_name>
4. Create a network
docker network create <network_name>
5. List all networks
docker network ls
6. Remove a network
docker network rm <network_name>
Inspecting Containers and Images
1. Inspect a container
docker inspect <container_id_or_name>
2. Inspect an image
docker inspect <image_id_or_name>
3. View container logs
docker logs <container_id_or_name>
4. Display resource usage statistics
docker stats
5. Access a running container's shell
docker exec -it <container_id_or_name> /bin/bash
The -it flag on the docker exec command functions to allow interactive interaction with the container terminal. Here is an explanation of each flag:
-i(interactive): Ensures the input session remains open, so that we can interact with the container through the given commands.-t(tty): Allocates a pseudo terminal (TTY) that creates an interactive terminal like the one we usually use, making it easier to run commands in text mode.
The -it combination is very useful for entering a shell inside a container and running commands directly
If you don't want any interaction inside the container (hit and run), you can ignore the -it flag
docker exec <container_id_or_name> <some command in container>
Docker Compose Commands
1. Start services in the background
docker-compose up -d
2. Stop services
docker-compose down
3. Build or rebuild services
docker-compose build
4. View logs of services
docker-compose logs
5. List all services
docker-compose ps