Docker provides a comprehensive set of commands that enable you to manage containers, images, networks, and other Docker objects effectively. Mastering these commands is essential for optimizing your Docker workflows, whether you're building images, running containers, or configuring networks.
Basic Docker Commands
These fundamental Docker commands are crucial for working with containers and images:
docker run
Purpose: Creates and starts a new container from a Docker image.
Example:
docker run -d -p 80:80 nginx
Runs an Nginx container in detached mode (-d), mapping port 80 of the container to port 80 on the host (-p).
docker ps
Purpose: Lists all running containers.
Example:
docker ps
Use -a to view all containers, including stopped ones:
docker ps -a
docker stop
Purpose: Stops a running container.
Example:
docker stop container_id
Replace container_id with the container's ID or name.
docker rm
Purpose: Removes a stopped container.
Example:
docker rm container_id
To remove all stopped containers:
docker rm $(docker ps -a -q)
docker rmi
Purpose: Removes one or more Docker images from your local system.
Example:
docker rmi image_id
To remove unused (dangling) images:
docker image prune
docker images
Purpose: Lists all Docker images on your local machine.
Example:
docker images
docker build
Purpose: Creates a Docker image from a Dockerfile.
Example:
docker build -t myapp .
Builds an image named myapp from the Dockerfile in the current directory.
docker pull
Purpose: Downloads a Docker image from a registry.
Example:
docker pull redis
Pulls the Redis image from Docker Hub.
docker push
Purpose: Uploads a Docker image to a registry.
Example:
docker push myrepo/myapp
Pushes the myapp image to the myrepo repository on Docker Hub or another registry.
docker exec
Purpose: Runs a command inside a running container.
Example:
docker exec -it container_id bash
Opens an interactive shell (bash) inside the specified container.
docker logs
Purpose: Fetches the logs of a running container.
Example:
docker logs container_id
Use -f to follow the log output in real-time:
docker logs -f container_id
Docker Networking Commands
Manage and configure Docker networks with these commands:
docker network ls
Purpose: Lists all Docker networks.
Example:
docker network ls
docker network create
Purpose: Creates a new Docker network.
Example:
docker network create mynetwork
docker network connect
Purpose: Connects a container to a network.
Example:
docker network connect mynetwork container_id
docker network inspect
Purpose: Displays detailed information about a network.