Docker Commands

  • docker pull <image-name> - fetches an existing image from Docker Hub. The image is saved on your machine, so don't forget to clean up unused images to free up space.
  • docker images - lists all the images saved on your machine.
  • docker run <image-name> - fetches the image from Docker Hub, creates a new container and then runs the executable.
  • docker run --rm <image-name> - same as docker run <image-name> with one addition: it deletes the container after it exits. It's particularly useful when you want to try some stuff once.
  • docker run -d <image-name> - same as docker run <image-name> with one addition: the container runs in the background. You can close your terminal, and it won't affect the container. It'll still run.
  • docker run -P <image-name> - same as docker run <image-name> with one caveat: it publishes the exported ports from the image to random ports on your machine. Basically, you get an URL where you can access the app.
  • docker run -d -P --name <your-custom-name> <image-name> - this commands reads as follows: run the <image-name> in detached mode, expose the ports and name the container <your-custom-name>.
  • docker run -p 8080:80 <image-name> - it allows you to specify where it should forward the requests to your host port. For example, all the requests made to port 8080 should be forwarded to the container's host 80. The configuration is YOUR_HOST_PORT:CONTAINER_PORT, where your host port is the port where you want to receive traffic and the container port is the host where the container listens for connections.
  • docker stop <container-id>/<container-name> - stops the container from running.
  • docker ps - lists all the running containers.
  • docker ps -a - lists all the containers on your machine. Both running and stopped ones.
  • docker rm <container-id> - removes a container.
  • docker rm $(docker ps -a -q -f status=exited) - removes all the containers with the status "exited".
  • docker volume create photos - it creates a new volume called "photos" for storing data (photos in this case).
  • docker run --name persist-photos -p 3000:80 --mount type=volume,source=photos,target=/app/photos photo-app
  • docker container prune - removes all stopped containers.
  • docker system prune - removes all stopped containers, all unused networks, all dangling images and unused build caches.