Docker Commands
Commands to get started with Docker
Website Visitors:If you’re new to Docker and need list of docker commands or you need a revise on the commands, this post is for you. We’ve listed out few Docker commands to get started with.
Pull and Start Containers
docker images or docker image ls - List all the local images in your machine.
docker pull imagename - Pulls an image from docker hub. Does not create any containers from it.
docker run imagename - To start an image and run it as container.
docker ps - List all running containers.
docker ps -a - List all stopped containers.
docker ps -a -q - List container ids for all the containers in your machine.
docker ps -l - Show last stopped container.
docker images -q - List image ids for all the images in your machine.
docker run imagename command: Start the image and run the command you specify. Ex: docker run ubuntu sleep 20
runs the ubuntu image and sleeps for 20 seconds.
docker logs containerName - Display logs from a container. If you’d like to view errors or any other information about your container output, you can do so by running the command. This will display logs about a container. Make sure that the container is not removed. Container can either be running or stopped.
docker run -ti - T is for terminal and i for interactive so this command runs a container in an interactive mode. At the end of the command, you have to specify what program should it run interactively. It works even if you do not specify any program. By default it will open terminal for you. You can specify any other programs as well. We’ve used bash in this example. Ex: docker run -ti ubuntu:latest bash
We are also explicitly specifying docker to run the latest ubuntu version. Even if we omit latest parameter, docker still pulls the latest image by default by showing this message in the output Using default tag:latest
-ti
parameter so that when started, it starts that terminal. If you only use bash with no -ti
parameter, when you start the container, it might try to start bash and if it cant, container will exit.When you use the docker run command, if the image is not available on your host, docker will download the image from docker hub and run it. This is done only for the first time. From next time, it will run the container from the image downloaded earlier.
docker start container_Name - starts a specific container that was already stopped earlier.
If you’re using docker start command, then you should -a (attach) parameter to it to start it in interactive mode. Ex: docker start -ai ContainerName (or containerid)
Stop or kill containers
docker stop container_Name - stops a running container. This is like using OS specific shutdown or reboot commands to perform the operation smoothly.
docker stop $(docker ps -a -q) - list and stop all the running containers.
docker stop xx xx xx xx - If you have multiple running containers, you can stop all of them at once by running docker stop and first two characters in the container id.
docker kill container_Name - sends a kill signal to the container. This is like pulling the power cable from a running machine.
Detach & Attach container
Use the -d
parameter to detach the docker from the console but the command will still run in background. Ex: docker run -d ubuntu sleep 100
. It will pull the ubuntu image if not found locally, run it in detatched mode, and run the command to sleep for 100 seconds.
docker run -dti ImageName - creates a container from an image, and exits/detaches it immediately. -d parameter is for detach. By default if you do not enter any command, it runs bash command. Ex: docker run -d -ti ubuntu
. To detach a container, you should press and hold ctrl key and then hit p q keys combination after you’ve connected to the container. After detached, you can connect to it again by attach command. As you’ve used -ti parameter, you will be connected to a terminal once you attach the container created above.
docker attach ContainerID/ContainerName - Use docker attach
to attach your terminal’s standard input, output, and error (or any combination of the three) to a running container using the container’s ID or name. This allows you to view its ongoing output or to control it interactively, as though the commands were running directly in your terminal.
You can also connect to the container that was stopped earlier using attach command. This command will also connect to containers started by docker start command.
|
|
If you run docker attach containerName
command in two different consoles (like cmd, or PowerShell console), you can still connect to both of them but all the commands executed on one console will be visible in other console, just like screenshare.
docker exec -ti ContainerName CommandName - Runs a command in a running container. Ex: run the command, docker run -d ubuntu sleep 100
. Next run docker exec container_Name cat /etc/hosts
. This will run the cat command in the running container.
If you want to connect to a single container through multiple consoles, you can run docker attach containername
command on one console and docker exec -ti ContainerName bash
on other console. If you’ve created any files in any of the console, they are visible in both the containers. But you cannot view commands executed in other console, just like multiple ssh connections to a linux server.
If you close the session created by docker attach
command, it will also close the session created by docker exec
as exec is just running commands on a running container.
Custom Name for the container
docker run -d --name webapp nginx
: This will create a container with
Docker Tags
In Docker, tagging an image is like giving it a name and version number. It helps you identify and manage different versions of the same image.
For example, if you have an image named “myimage” and you want to tag it with version “v1.0”, you would use the following command:
|
|
This command assigns the tag “myimage:v1.0” to the image “myimage”.
Create Docker image
docker commit - creates an image from a stopped container. Docker run creates a container from an image, and docker commit creates an image from a stopped container.
docker commit ContainerID - convert a container to an image. From here, you can run docker run -ti ImageName
to create a container from the image you’ve created.
You can commit a container into an image and name it in single command as docker commit ContainerName(or containerID) YourImageName
docker run –rm -ti ImageName command - This whole command will create a container from the image name, run the command you specify, display output on the console and then delete the container immediately. Ex: docker run --rm -ti ubuntu ls
Let’s say you’ve used ubuntu image and created a custom image by installing few softwares and ping command. You can create an image from that container by running the below command. It will create new image with custom name. Here, -m parameter is for providing commit message for your new image.
docker commit -m “Commit Message” ContainerName NewImageName:tag
Ex: docker commit -m “UbuntuWithPing” pingwithubuntu localubuntu:latest - Here, pingwithubuntu is the container name which has ping tools installed. localubuntu is the new image name.
Listing all Docker resources
Use docker resource with -a
(stands for –all) parameter to list all resources including running and stopped resources . Ex: docker images -a
or docker ps -a
Listing only Docker resources id
Use docker resource with -q
parameter to list the id of the resource. You can use these commands in combination with docker rmi or docker rm to remove all the resources. Ex: docker images -a
or docker ps -a
Docker Inspect & Logs
docker inspect containername or id
- The “docker inspect” command is used to obtain detailed information about a container, image, or network.
docker logs containername or id
- The “docker logs” command is used to view the logs of a specific container.
Docker History
If you’d like to view the series of steps performed in a container creation, use docker history containerid/imageName
command. Ex: docker history mywebapp
Here, mywebapp is the name of the container.
View Docker Disk Usage
In order to find the actual disk size used by docker, run below commands on the docker host.
docker system df
command shows actual docker disk usage on the machine.
docker system df -v
: breakdown of above command.
Passing Variables At Docker Run
If you’d like to send a parameter to docker run at the command runtime, you can specify using the -e
parameter as shown below:
docker run -d --name mysql-db -e MYSQL_ROOT_PASSWORD=db_pass123 mysql
Here, using the -e parameter you are setting the sql root password.
You can also set variables in docker compose and dockerfile as given below
|
|
In this example, the MY_VAR
environment variable will be set to "hello world"
inside the container.
|
|
In this example, the MY_VAR
environment variable will be set to "hello world"
inside the container.
Docker Volumes
A Docker volume is a directory that is shared between the host machine and a container. It allows you to persist data even after the container is deleted or restarted.
Creating a Docker Volume
Here are the steps to create a Docker volume:
Method 1: Using the docker volume create
command
|
|
This will create a new volume named my-volume
.
Method 2: Using the docker run
command with the -v
flag
|
|
This will create a new volume named my-volume
and mount it to the /app/data
directory inside the container.
Method 3: Using a Docker Compose file
|
|
This will create a new volume named my-volume
and mount it to the /app/data
directory inside the container.
Deleting resources
Deleting unused resources
docker system prune - Delete all unused images, containers, volumes and networks which are not tagged or not associated with any container.
docker system prune -a - Same as above but it will also remove all stopped containers as well.
Removing Docker images
docker rmi image_name_or_id OR docker image rm image_id - delete image from your machine.
docker rmi $(docker images -a -q) - Delete all images.
docker image prune -a - removes all images that doesnt have containers
docker builder prune -a - removes all docker build cache.
Removing Containers
docker rm $(docker ps -a -q) - Delete all stopped containers
docker rm container_name - Remove a specific container.
docker rm container1 container2 container3 - Removes multiple containers. You can also use first few numbers in container name when using docker rm command.
docker rm $(docker ps -a -f status=exited -q) - Remove all the containers that are in exited state.
Removing Containers with a pattern
If you want to identify all the running containers and stop them in Linux OS, you can use the below command.
|
|
Let’s look at the above command step by step: docker ps -a
is for finding all the containers. We are sending the information into grep which is a Linux command used to find strings in expressions. We can use this command to find a value in our output. Running containers have status as ‘Up X seconds’. So, we are searching for the word “Up” in the output. When you run docker and grep commands, it will show the entry which has that value.
|
|
Next, we need the id of that container. So we use awk '{print $1}'
. Finally, using xargs, we send that id to docker stop
command.
|
|
Removing resources with multiple patterns
You can use multiple filters in identifying a resource and then remove it. You should specify -f
parameter with your filter pattern as shown below.
docker ps -a -f status=exited -f status=created
docker rm $(docker ps -a -f status=exited -f status=created -q)
Removing dangling images
Dangling images are untagged docker images that are not used by any container. Dangling images also mean that you’ve created new build of the image but haven’t specified any name yet. By default docker images consists of several layers. Dangling images are layers with no relationship to any tagged images. They cannot be used for creating containers and they consume space unnecessarily. These dangling images can be identified by using -f
parameter and using dangling=true
value to docker images command.
|
|
Removing Volumes
docker volume ls - List all volumes in your machine.
docker volume rm volumeName - Delete volume from your machine. You can also use multiple volume names as: docker volume rm volumeName1 volumeName2
docker volume ls -f dangling=true - List all dangling (Volume exists but no longer connected to a container)
Run and remove container
docker run –rm -ti ImageName command - This whole command will create a container from the image name, run the command you specify, display output on the console and then delete the container immediately. Ex: docker run --rm -ti ubuntu ls
Remove container and its volume
docker rm -v Container_Name - Removes container and its volume.
If you use -v
flag, all the unnamed volumes for a container can be deleted along with the container. This only works with unnamed volumes. In the output, you wont see any reference to removal of the volume. If the volume is unnamed, it will be silently removed. If it is named volume, it stays present.
Docker Build
The Docker build cache is not limited to the current folder, but it’s also not global across all folders.
When you run docker build
, Docker creates a cache of the build process in the following locations:
- In-memory cache: Docker stores the build cache in memory during the build process. This cache is lost when the build process completes or is interrupted.
- Disk cache: Docker also stores the build cache on disk in the following locations:
- On Linux:
/var/lib/docker/build-cache
- On Windows:
C:\ProgramData\Docker\build-cache
- On macOS:
~/Library/Containers/com.docker.docker/Data/build-cache
- On Linux:
The disk cache is persisted across builds, so if you run docker build
again with the same Dockerfile and build context, Docker can reuse the cached layers.
However, the cache is tied to the build context, which includes the following:
- The Dockerfile
- The build directory (i.e., the current working directory)
- The files and directories in the build directory
If you change any of these factors, the cache is invalidated, and Docker will rebuild the image from scratch.
Here are some scenarios to illustrate this:
- If you run
docker build
in a different folder, the cache is not shared between folders. - If you modify the Dockerfile, the cache is invalidated, and Docker will rebuild the image.
- If you add or remove files in the build directory, the cache is invalidated, and Docker will rebuild the image.
- If you use a different build context (e.g., a different directory or a different Dockerfile), the cache is not shared between contexts.
To share the cache across builds, you can use the --cache-from
flag, which allows you to specify a previous build’s cache as a starting point for the new build. This can be useful when you’re building multiple images with similar dependencies.
To completey remove the cache, use docker builder prune -a
.
Run Specific Image Version
When you directly run docker run ubuntu
it pulls the image with latest
tag and runs it. When you do not specify any tag, this is what happens. If you want to run a specific version of an image, you have to specify the version you want. Ex: docker run ubuntu:22.04
Save Docker Data
Let’s say you’ve created mysql container from mysql image and destroy the container. All the data that you’ve created in the mysql container is lost when it is destroyed. If you want to save the data, you have to map a folder on the docker host to the container.
docker run -v /opt/mysqldata:/var/lib/mysql mysql
- This command runs the mysql container, and maps mysqldata folder on your docker host to the /var/lib/mysql folder inside the container. When docker container runs, it mounts the external folder in the container. When it is deleted, the mount is deleted but the data persists in your docker host folder (/opt/mysqldata in this example).
Similarly, you can run jenkins with the command: docker run -u 0 -p 8082:8080 -v /root/JenkinsData:/var/jenkins_home jenkins/jenkins
. Here, you are mapping docker port 8080 to 8082, and the jenkins data in your container’s /var/jenkins_home folder is mapped to /root/JenkinsData folder in your docker host. -u 0 is for specifying root user. Using -u parameter you can run this command as different user.
Memory and CPU limits
You can set memory and CPU restrictions in docker run command so that the docker container will not consume all your host’s resources and make it slow. Here is an example on setting 6 MB memory and starting ubuntu image.
|
|
There are different options in setting up cpu restrictions in docker. You can find the full list here: Docker run. Below example restricts 1 cpu to the container created.
|
|
Docker port
When docker containers need to communicate with the machines outside docker, they use an internal port and map it to a port outside docker. For example, if you have a web server in docker which runs on port 4444, you can map it to an external port which can be 4444 or any unused port number in your machine aka docker host.
docker run -d -p 4444:4444 --name SeleniumWeb selenium/hub
Here, first 4444 is on the docker host machine and second 4444 is a internal docker port number. You can also run it with a different external port as shown below.
docker run -d -p 4444:2222 --name SeleniumWeb selenium/hub
You can also specify a protocol, TCP or UDP while entering the port number as shown below
docker run -d -p 45678/UDP --name SeleniumWeb selenium/hub
You cannot map to same port on the docker host more than once. If you use a free port like 4444 on docker host, you cannot use it for another docker instance.
If you do not specify any external port number, docker will automatically assign a free/random port on your machine to that container. How do you find which port number is used externally? Let us know in the comments.
Find docker port
docker port ContainerName - check docker port mapping to the real world port. This will be useful if you’ve set a docker port internally but did not choose any external port.
If you have only one container and don’t know its name, you can run docker port $(docker ps -a -q)
to find port numbers used by that container. Note that if you have multiple containers this command will not work.
Docker Prune
docker image prune - This command will remove all dangling images.
docker container prune - This command will remove all stopped containers.
Important Points
-
Command syntax for docker on windows and docker on linux is different. In docker for linux,
docker exec containerName cat /etc/*release*
works. But in docker for windows it fails. Similarly, when you run a web image in docker on windows, you have to use the ip of your windows host (windows machine) to access that webpage. But if you have installed docker on linux, you can access the web page using the docker ip directly. -
By default docker runs containers in non interactive mode. It means, docker runs the image, creates a container and exits immediately.
Question:
Deploy a mysql
database using the mysql:5.6
image and name it mysql-db
. Attach it to the newly created network db-mysql-network
Set the database password to use db_pass
. The environment variable to set is MYSQL_ROOT_PASSWORD
.
Solution:
docker run --name mysql --network db-mysql-network -e MYSQL_ROOT_PASSWORD=db_pass mysql:5.6
Question:
Deploy a web application named webapp
using the mysql
image. Expose the port 8080 on the container to 38080 on the host.
The application makes use of two environment variable:
1: DB_Host
with the value mysql-db
.
2: DB_Password
with the value db_pass123
.
Make sure to attach it to the newly created network called db-mysql-network
.
Also make sure to link the MySQL
and the webapp
container.
Solution:
docker run --network=db-mysql-network -e DB_Host=mysql-db -e DB_Password=db_pass123 -p 38080:8080 --name webapp --link mysql-db:mysql-db -d mysql
In this tutorial, we’ve explained how to add additional resources to your infrastructure. We’ve also demonstrated examples for all the topics that are discussed. We hope you have learned something new in this article.
Did you try setting up memory and cpu restrictions in docker run command? If you’ve tried, set memory less than 5 MB and check the result. Let us know the output in the comments section below.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.