You are currently viewing Useful Docker Commands

Useful Docker Commands

Introduction

A practical summary of the most useful docker commands.

VRequirements
Installed Docker on Windows or Linux

Container operations

1) Run a container in detached mode
$ docker run --restart=always --rm --expose=22 --network=net-nam -dit --name=centos --label environment=dev centos:latest /bin/bash
  • -d option starts the container in the detached mode
  • -i option starts the container in the interactive mode
  • -t option allocates a pseudo-tty and attaches it to the standard input
  • –restart=always setting the restart policy on a container
  • –expose=22 to expose port 22 while starting a container
  • –label environment=dev labelling a container
  • –network=net-name to start container on host network, default is bridge
  • –rm to remove container after stop
  • –name=centos is the container name, if not specified will be chose randomly
  • centos:latest are the docker image name and relative version
2) Attach to an existing container shell
$ docker exec -it container-name bash
3) List both running and stopped containers
$ docker ps -a
4) Stop all containers
$ docker stop 'docker ps -q'
5) Delete all containers
$ docker rm 'docker ps -a -q'
6) Executing bash command after start
$ docker run -d centos /bin/bash -c "while [ 1 ]; do echo hello docker ; sleep 1; done"
7) Transfer this file into the container and viceversa
$ docker cp file-to-copy.txt container-name:/path/to/copy

Image operations

1) Pull an image, if tag is omitted docker pull last one
$ docker pull image-name[:tag]
2) List images
$ docker images
3) Delete all images
$ docker rmi 'docker images -q'
4) Delete all dangling images
$ docker rmi -f $(docker images -f "dangling=true" -q)
5) Remove all unused images, not just dangling ones
$ docker image prune -a

Volume operations

1) Delete all volumes
$ docker system prune --volumes
2) Remove a specific volume
$ docker volume rm volume-to-remove

Network operations

1) Create a network
$ docker network create network-name
2) Remove all unused networks
$ docker network prune

Leave a Reply