Common usage of Docker

Matt Wang
2 min readJul 2, 2021

Test docker environment

docker run --rm hello-world# --rm Automatically remove the container when it exits
# hello-world is the image name. If it does not exist locally, docker will pull down the image and run it

Run an interactive shell

docker run --rm -it ubuntu bash
# -it is short for --interactive/-i --tty/-t
# --interactive Keep STDIN open even if not attached
# --tty Allocate a pseudo-TTY

Sometimes there is no bash in images, sh can be used

docker run --rm -p 8088:80 -it docker/getting-started sh
# -p/--publish host_port:container_port
# docker/getting-started is image name

Connect to a running container

docker exec -it <container name> /bin/bash
# Or
docker exec -it <container name> /bin/sh

Install tools when needed

# Install ping and ip commands
apt-get update
apt-get install iputils-ping iproute2

View docker containers, images, volumes and networks

# List all containers
docker ps -a
# List all image
docker images
# List all volumes
docker volume ls
# List all networks
docker network ls

Create a new network

docker network create -d bridge my_bridge

Docker will allocate a new subnet to the new network. Typically, the IP address pool looks like 172.18.0.0/16.

Access other containers by name

Prerequisite

  1. Create a user-defined network
  2. Run containers with names and connect them to the user-defined network

Samples:

# Create a user-define network
docker network create -d bridge my_bridge
# Run the first container with name container1, and connect it to my_bridge
docker run --name container1 --net my_bridge -it busybox sh
# Run the second container with name container2, and connect it to my_bridge
docker run --name container2 --net my_bridge -it busybox sh

Access containers by name:

# In container1,
ping container2
# In container2,
ping container1

References:

  1. https://www.tutorialworks.com/container-networking/
  2. https://docs.docker.com/engine/reference/commandline/run/
  3. https://docs.docker.com/engine/tutorials/networkingcontainers/

--

--

Matt Wang

Empowering others through handy and innovative tech solutions and sharing knowledge. Stay tuned with my new articles.