Docker commands

unpublished draft
Docker

Images#

Container#

Adhoc commands#

# Grant permission to docker deamon socket
sudo chmod 666 /var/run/docker.sock

# Copy a file from outside into container
# docker cp D:\Temp\test.txt sql-server-dev:/home
docker cp [File path] [Container name or Id]:[Path inside the container]
docker cp [Container name or Id]:[/file/path/within/container] [/host/path/target]

# Get to see container log
docker logs [container id]
# Attach a bash session to a running container
docker exec -it [container id] /bin/bash

# Build an image - Need Dockerfile in the context
docker build -t [tagName] [context]
# For Ex: docker build -t local-dev/react-test .
# Run container: docker run [-it] -p 3000:3000 local-dev/react-test

# List all network
docker network ls
# Network information
docker network inspect [network name]
# Create a network
docker network create [network name]
# Remove a network
docker network rm [network name]

# List all images
docker image ls -a
# Remove an image
docker rmi [image name]

# List all container
docker container ls -a
# List all running container
docker container ps
# Remove an container
docker rm <container-id>
# Get docker logs
docker logs <container-id>

Persistence data between container#

Recommended using docker volume

# Create volume
docker volume create [vol_name]

# Remember to stop whichever container using the volume
# Create another container and mount existing volume into it
docker run -v [vol_name]:/data_to_bk --name [temporary_container_name_bk] ubuntu /bin/bash

# Run one time container that backup data from volume of container above to host path
docker run --rm --volumes-from [temporary_container_name_bk] -v [host_path]:/backup ubuntu tar cvf /backup/backup.tar /data_to_bk

---
# Remember to create the new container first
docker run -v [vol_name]:/data_to_restore --name [temporary_container_name_rs] ubuntu /bin/bash

# Restore the data to corresponding to target volume
docker run --rm --volumes-from [temporary_container_name_rs] -v [host_path]:/backup ubuntu bash -c "cd /data_to_restore && tar xvf /backup/backup.tar --strip 1"

# Example
docker run --rm --volumes-from restore_pg -v x:/volumebackup:/backup ubuntu bash -c "cd /data_to_restore && tar xvf /backup/backup_postgres_20220717.tar --strip 1"

Khanh Nguyen

Web developer & .Net lover