Docker useful commands

Build a container from Dockerfile

docker build -f Dockerfile -t my_image . # note that is a dot at the end

Run docker container

docker run -it my_image bash

List Docker local images

docker images

List docker processes

docker ps

# or list all (including stopped processes)
docker ps -a

Stop containers

# stop all containers
docker stop $(docker ps -aq)

# or stop specific container by id or by name
docker stop <container_id_or_name>

Delete all containers

docker rm $(docker ps -aq)

Start a container

# using image name
docker run -it python:3.6 /bin/bash

# or using image id
docker run -it 8dbd9e392a96 /bin/bash

Get inside a container

# get running containers
docker ps

# get inside a running container
docker exec -it <container_id> bash

# if the above command does not work because of bash is not found, run with shell
docker exec -it <container_id> sh

Delete specific docker container

docker rm <container_id>

Delete specific docker image

docker rmi <image_id>

Docker - How to cleanup (unused) resources

Once in a while, you may need to cleanup resources (containers, volumes, images, networks) ...

delete volumes

# see:
docker volume rm $(docker volume ls -qf dangling=true)
docker volume ls -qf dangling=true | xargs -r docker volume rm

delete networks

docker network ls  
docker network ls | grep "bridge"   
docker network rm $(docker network ls | grep "bridge" | awk '/ / { print $1 }')

remove docker images

# see:
docker images
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
docker images | grep "none"
docker rmi $(docker images | grep "none" | awk '/ / { print $3 }')

remove docker containers

# see:
docker ps
docker ps -a
docker rm $(docker ps -qa --no-trunc --filter "status=exited")

Resize disk space for docker vm

$ docker-machine create --driver virtualbox --virtualbox-disk-size "40000" default

Docker compose commands

# start containers and display containers logs in terminal
docker-compose up

# start containers in detached mode, terminal is released and no logs are displayed
docker-compose up -d

# start containers and force build
docker-compose up --build

# stop running containers
docker-compose stop

# delete containers
docker-compose stop

More options for run command

docker run --rm -v $(pwd)/project:/project -w /project -it my_image /bin/bash
  • --rm will automatically clean up the container and remove the file system when the container exits
  • -v mount volume to the container
  • -i interactive mode