Docker CLI commands cheatsheet

Docker build #

docker image build -t <projectname>:<tag> .

Build Docker image from custom filename (Not Dockerfile) #

docker build -f nginx_build_from_source .

Existing image tag #

docker image tag <image_id> <repo_name>/<image_name>:<version>

Passing proxies to build image #

docker image build --build-arg http_proxy=<http_proxy> --build-arg https_proxy=<https_proxy> --build-arg ftp_proxy=<ftp_proxy>

Run named container #

docker container run -it --name containerName image:tag 

Specify container port #

docker run -p 3000:8000 python-project 

Docker container specific commands #

# View container logs
docker container logs <container_id>
docker container logs -f <container_id>

# Remove stoped container automatically
docker container run -it --rm  -p 4000:8000 python-project  
# When giving the flag --rm on the run of the container, docker will automatically destroy the stopped container without doing it manually

# Remove a stopped container
docker container rm <container name>

Run container in detached mode #

docker container run -it -d image:tag

Real time containers statistics  #

docker container stats 

Always restart container run command #

docker container run --restart always image:tag 

Run interactive container shell  #

docker exec -ti <container_id> bash

Docker Network commands #

# List the docker networks 
# bridge is the default network that will be created if we dont create a custom one 
docker network ls 

# Network Specifications 
docker network inspect <network_name>

# Check container’s IP address
docker exec containerName ifconfig 

# ping from one container through another 
docker exec <source_container_id> ping <destination_container_id>

Custom Networks

Let’s say that we want to use a container which is our DB inside our Django app which is in another container, that means that we would need to find the container IP that the DB is running and hardcode it into our Django app. 

When creating custom network, docker will automatically configure the DNS for us and we will be able to talk to another container by its name 

# Create network
docker network create --driver bridge firstnetwork 

# Register our containers to our custom network 
docker run --net firstnetwork <container>:<tag>

we can now use our container name “redis” like this in our code 

Map volume to the container  #

docker run -v C:\Users\akent\Projects\Python\Docker\PythonProject1:/app <container>:<tag>

Docker Security Best Practices #

Run docker commands with non-root user #

sudo usermode -aG docker <user> 
# to add the user you are currently logged in to the docker group, specify $USER instead of <user>

/*54745756836*/

Powered by BetterDocs

Leave a Reply