Essential Docker CLI Commands You Need to Know

docker --version

  • To get the docker version

docker pull <image_name>

  • To Download container image from container registry

  • Container Registry - https://hub.docker.com/

  • e.g. docker pull ubuntu

docker images

  • Get the list of container images in local machine

docker run <image_name>

  • To create and execute a container based on the image name.

  • If the image is not downloaded it will first pull and then execute the container

docker ps

  • Get the list of active/running containers in the local machine

  • List is shown empty as there is no active containers so containers go into exit state immediately.

docker ps -a

  • Get the list of active/running as well as inactive/stopped containers in local machine.

Modes of Container Execution

Foreground/Attached Mode

  • It is a default mode of execution

  • It runs the container by consuming the terminal

  • The terminal will be released, only when the container goes to exit state

Background/Detached Mode

  • The terminal is accessible while running the container is background/detached mode.

  • docker run -d <image_name>

Interactive Mode

  • To run and login to the container

  • docker run -it <image_name>

docker start <container_id>

  • To start the container

docker exec -it <container_id> bash

  • Login to the running container

docker stop <container_id>

  • Stop the container

docker rm <container_id>

  • Remove the container from the local machine

docker rm -f <container_id>

  • Force - Remove the Container from Local Machine

    • When container is in running state, we are not able to delete the container using just rm command so we need to use rm -f to forcefully delete the container.

docker rmi <image_name>

  • Remove the container image from local machine.

  • When removing container, if there is any container running using that container image then error will be shown, so we need to first delete those container then remove the container image.

docker rmi -f <image_name>

  • Force - Remove the container image from local machine.

  • As said, When removing container, if there is any container running using that container image then error will be shown, so we can forcefully remove the image using this command.

  • This is not the best practice