Skip to content

Instantly share code, notes, and snippets.

@percyvega
Last active April 25, 2023 14:28
Show Gist options
  • Save percyvega/46bf5101f31624ca1a0767e474a9befb to your computer and use it in GitHub Desktop.
Save percyvega/46bf5101f31624ca1a0767e474a9befb to your computer and use it in GitHub Desktop.

Help

$ docker --help
$ docker image --help
$ docker image ls --help

Versions

See the Docker version
	$ docker --version
See the Docker client and server versions
	$ docker version

List

docker image ls
docker container ls
docker network ls
docker volume ls

Delete

docker image rm -f $(docker image ls -q)
docker container rm -f $(docker container ls -a -q)

docker

info
--help
system df
	to see space usage
system prune
	to remove dangling (not associated to a container) images, containers, volumes, and networks
	-a
		also remove stopped resources
search [keyword_to_search_in_repository_registry]
	To find an image. Same as doing it from https://hub.docker.com
login
	To login to your Docker.com account

IMAGES

An image is every file that makes up just enough of the Operating System to perform a task.
The Dockerfile provides the instructions to build a container image using the 'build' command.
It starts from a previously existing Base image (through the FROM clause) followed by any other needed Dockerfile instructions.

$ docker image...

ls
	list all images
pull [image_name]
	downloads the latest version of image to local repo. This is done automatically when you 'docker container run...'
		e.g. docker image pull centos
		e.g. docker image pull centos:latest
history [image_name]
	show history of image changes or additions
inspect [image_name]
	see all configurations and properties
tag [image_name] [new_image_name]
	associates a new tag to an existing tag
	e.g. $ docker image tag old_name:old_version new_name:new_version
push [image_name]
	pushes image to Docker Hub
		e.g. docker image push percyvega/nginx

CONTAINERS

The image at runtime; it's a process. There can be multiple containers off the same image.
Uses an image and creates from it a container with a running process.

$ docker container...

ls
	list all running containers
	-a
		list all running and non-running containers
	-l
		list the last container run
commit [container_name] [[image_name:image_tag]]
	creates a new image from a container
start [container_name]
	start an existing container currently stopped
stop [container_name]
	stop a container gracefully (if that doesn't work after a few seconds, then forcefully)
	crtl + d
		if you are inside the main process, this will stop the container (same as exit in bash)
kill [container_name]
	stop a container forcefully
attach [container_name]
	jump into the main process of the container
	ctrl + p, ctrl + q
		to detach (jump out) of the container without stopping it
exec -ti [container_name] [[process_to_run]]
	connect to a running container and execute a (non-main) process
	e.g. exec -ti [container_name] bash
rm [container_name]
	remove a container that is not running
	-f
		remove a container forcefully (even if it’s running)
	e.g. docker container rm -f $(docker container ls | grep percyvega_hello | awk '{print $1}')
logs [container_name]
	look at logs
	-f
		look at logs by tailing them
inspect [service_id]
	see all configurations and properties
	--format <json path>
		to find a specific value
			e.g. docker inspect --format '{{.State.Pid}}' percy_new
stats [container_name]
	see usage statistics of the container

$ docker container run [-options] <image_name[:tag]> [process_to_run]

Same as `docker run ...`
Creates a new container from an image and runs it
	e.g.
		$ docker container run -d -p 27017:27017 --name mongo_trs mongo:4.4.19 
		$ docker container run -p 8080:8080 --name my_container_name my_image_name
		$ docker container run -ti <image_name> bash
		$ docker container run -d -ti <image_name> bash
		$ docker container run --rm -ti <image_name> bash -c "sleep 5; echo all done"
image_name
	name of the image from which the container will be created
process_to_run
	name of the process to execute. This is the main process of the container.
	The container will stop as soon as this specific process stops.
--rm
	Delete the container when its main process stops.
-ti
	For manually running commands.
	terminal interactive, tty (-t, terminal on foreground) and interactive mode (-i)
-d
	detached mode; to leave the container running in the background instead of hanging the terminal until exit.
--name [container_name]
	give this container a specific name
-p [external_port:internal_port]
	the container will expose its internal port to the external port
	if external_port is not specified, Docker randomly chooses one available.
	To show the port for a running container, you can enter:
		$ docker ports [container_name]
--privileged=true
	to turn off some of the Docker security features
--pid=host
	to turn off even more of the Docker security features

Volumes:

- Two main varieties: Persistent and Ephemeral (unpopular).
- Volumes are the best alternative for holding state between container runs.
- Volumes can safely be shared between several running containers.
- Volumes are not part of images. Docker manages its state.
- Shared container resource (folders or files) are created automatically.
- Sharing persistent data between host and containers
	- Ensure specified host folders and files exist before mapping.
	- Specified container folders and files will be created if they don't exist.
		e.g.
		docker container run -ti -v [host_file_path]:[container_file_path] [image_name] [process_to_run]
		docker container run -ti -v [host_folder_path]:[container_folder_path] [image_name] [process_to_run]
		$ echo "<h1>Hello from Host</h1>" > ./target/index.html
		$ docker container run -it --rm --name nginx -p 8080:80 -v "$(pwd)"/target:/usr/share/nginx/html nginx
- Sharing ephemeral data between containers
	- Shared "disks" that exist only until the last container uses it.
		e.g. docker container run -ti -v [container_folder_path] [image_name] [process_to_run]
			then the other containers have to run
				docker container run -ti --volumes-from [the_other_container_path] [image_name] [process_to_run]

Networking:

- Programs in container are isolated from the internet by default.
- You can group your containers into "private" networks.
- You explicitly choose who can connec to whom.
- Use host.docker.internal to refer to the container's hosting pod.
$ docker network
	ls
		will show the networks created by default to be used by containers
			- bridge: by default
			- host: that need to access the host's networking stack; turns off all the protections
			- none: with no network at all
	create [network_name]
		this will create a network to which containers will be able to connect
			$ docker container run --rm -ti --net [network_name] ubuntu bash
				this container will join a network with name [network_name]
	connect [network_name] [container_name]
		will make [container_name] join the [network_name] network

DOCKERFILES (Dockerfile)

- A Dockerfile is a simple text file that contains a list of commands that the Docker client calls while creating an image.
- Each line in the Dockerfile file is its own call to `docker run...` and then its own call to `docker commit...`.
- Each command takes the image from the previous line and makes another image.
- If you need to have one program start and then another program start, they need to be on the same line, so that they are in the same container.
- Environment Variables persist across lines if you use the ENV command to set them.
- Processes you start on one line will not be running on the next line.
- It's a simple way to automate the image creation process.

Commands:

FROM <image_name:[tag]> [as <stage_name>]
	FROM must be the first command in the Dockerfile.
		e.g. FROM ubuntu
	A Dockerfile can have multiple FROM statements, where you can copy artifacts from one stage to another.
		e.g. to first build and then to run the application using the same Dockerfile.
			- FROM maven ...
			- FROM openjdk:jre ...
RUN
	to run a command through the shell.
		e.g. RUN unzip install.zip /opt/install/
		e.g. RUN echo hello docker
		e.g. # Install Node
			RUN apt-get update \
			&& apt-get install curl -y \
			&& curl -fsSL https://deb.nodesource.com/setup_14.x | bash \
			&& apt-get install -y nodejs \
			&& npm install

CMD
	If there are multiple CMD instructions, only the last one will take effect.
	Provides default commands to execute when the container launches.
	Runs a command when the container starts.
		e.g. CMD ["java", "-jar", "/absolute_or_relative_to_WORKDIR/myapp-1.0-SNAPSHOT.jar]
	replaced if a command is specified at the end of docker run [image_name]...
COPY
	used to add a local file/directory into the image file system path.
		e.g. COPY run.sh /run.sh
	Can be used with --from when running on a different stage
		e.g. COPY --from=<another_stage> /my/files/target /opt/target
ADD
	used to add a local file/directory, compressed file contents, or remote file URL into the image file system path.
		e.g. ADD run.sh /run.sh
	add the contents of a tar archive (uncompressed)
		e.g. ADD PromiseRejectionEvent.tar.gz /install/
	add the contents of a URL
		e.g. ADD https://download-files.com/percy.mp3 /music/
ENV
	add environment variables to both the Dockerfile and to the resulting image.
		e.g. DB_PORT=5432
		e.g. ENV _JAVA_OPTIONS '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005'
		e.g. ENV SPRING_PROFILES_ACTIVE secure
ENTRYPOINT
	the command to run when the container runs
	allows for the user to specify arguments to this entry point by appending them after the image_name
		e.g. ENTRYPOINT ["/usr/local/bin/java.sh", "-Djava.security.egd=file:/dev/urandom","-jar","/usr/local/bin/app.jar"]

EXPOSE
	maps ports into a container
		e.g. EXPOSE 8080
VOLUME
	defines shared or ephemeral volumes
		e.g. VOLUME ["/host/path/" "/container/path/"]
			VOLUME ["/shared-data"]
WORKDIR
	sets the directory the container starts in
		e.g. WORKDIR /install/
USER
	sets the user the container will run under
		e.g. USER root
		e.g. USER ${SERVICE_USER} # back to not root (read-only)
		e.g. USER 1000

Build an image from a Dockerfile

docker image build -t <name:[tag=latest]> <build_context=.>
	Creates an image created using the Dockerfile in . directory
	e.g. docker image build -t my_name:my_tag ./new_image
	e.g. docker image build -t my_image:1.0 .
	e.g. # pack everything a Java/Spring application needs, create image, run image
		mvn -Dmaven.repo.local=./repository clean package
		docker image build -t percyvega/hello .
		docker container run -p 8080:8080 --name percyvega_hello percyvega/hello
If no tag is provided, then the latest tag is used.

Dockerfile examples

FROM maven:3.5-jdk-8 as BUILD
COPY . /usr/src/app
WORKDIR /usr/src/app
RUN mvn -Dmaven.repo.local=./repository package
FROM openjdk:8-jre
EXPOSE 8080 5005
COPY --from=BUILD /usr/src/app/target /opt/target
WORKDIR /opt/target
ENV _JAVA_OPTIONS '-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005'
CMD ["java", "-jar", "hello-docker-k8s.war"]

FROM ubuntu as builder
RUN apt-get update
RUN apt-get -y install curl
RUN curl https://google.com | wc -c > google-size
ENTRYPOINT echo google is this big; cat google-size
FROM alpine
COPY --from=builder /google-size /google-size
ENTRYPOINT echo google is this big; cat google-size
# then build with: docker image build -t hellojava .
# then run with: docker container run --rm -ti hellojava bash

FROM openjdk:alpine
COPY myapp/target/myapp-1.0-SNAPSHOT.jar /deployments/
CMD java -jar /deployments/myapp-1.0-SNAPSHOT.jar

DOCKER COMPOSE (docker-compose.yml)

  • Docker Compose is a tool for defining and running multi-container applications.
  • The context of all operations is the default: current folder name context.

docker compose...

up
	Start docker compose
up -d
	Start docker compose in detached mode
-f docker-compose.yml up
	Start docker compose with a non-default docker-compose.yml file
-p non-default-context up
	Start docker compose with a non-default context
ls
	List name and status of docker compose components
ps
	List information for all docker compose components
logs -f
	Look at all logs by tailing them
stop
	Stop all services
down
	Delete all services

Examples

version: "3.9"
services:
	web:
		image: "jboss/wildfly"
		volumes:
			- ~/deployments:/opt/jboss/wildfly/standalone/deployments
		ports:
			- "8080:8080"


version: "3.9"
services:
	web:
		image: "arungupta/couchbase-javaee:travel"
		environment:
			- "COUCHBASE_URI=db"
		ports:
			- "8080:8080"
			- "9990:9990"
		depends_on:
			- "db"
	db:
		image: "arungupta/couchbase:travel"
		ports:
			- "8091:8091"
			- "8092:8092"
			- "8093:8093"
			- "11210:11210"

docker-compose.override.yml
version: "3.9"
services:
	web:
		ports:
			- "80:8080"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment