Docker Quick Ref.
What is containerization ?
A way of packaging applications and its dependencies which can then run on a compatible runtime.
docker
One of the most popular container runtimes. The best way of learning docker and its fundamentals is docker-desktop. Install for your OS and follow the examples. It also comes with a kubernetes cluster.
Dockerfile
Project file that consists of step by step instruction to perform on a base OS image.
# base image
FROM openjdk:11
# steps
COPY app.jar /usr/src/project
WORKDIR /usr/src/project
# command to execute
CMD ["java", "-jar", "app.jar"]
docker build
Once a dockerfile is written the next step is to build the image. Image is nothing but a container which is not running yet.
docker build -t <repository:tag> <dockerfile_path>
once the build is done you can see the built image using:
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
docker run
Easiest way to run the image is:
docker run -p hostPort:containerPort <repository:tag>
and access the application using hostPort
. For more options see the docs
runtime logs and image/container cleanup is not in the scope of this quick ref discussion.
docker compose
In most application deployments there are multiple services that run together and communicate with each other. docker compose
lets you define those dependencies and make the networking happen.
Here is an example docker-compose YAML file that runs two images, one web application and one database together and lets them address each other internally. Notice the use of db
as a dependency and in datasource URL instead of IP or host name. docker compose takes care of passing the relevant environment variables while running the images as per the dependency requirement.
version: "3"
services:
db:
image: "postgres"
ports:
- "5432:5432"
environment:
POSTGRES_DB: testdb
POSTGRES_USER: testuser
POSTGRES_PASSWORD: testpass
app:
build: .
ports:
- "80:8080"
environment:
DB_URL: jdbc:postgresql://db/testdb
DB_USERNAME: testuser
DB_PASSWORD: testpass
depends_on:
- db
docker compose up