
How to containerize an application using Docker
In this article, we’re going to demonstrate how to package an application into a Docker image. A Docker image is a template that contains everything the application needs to run i.e. the binary/jar, the runtime, libraries, etc. Docker images can run with Kubernetes or similar tools which helps to simplify deploying applications.
Containerizing a Java/Kotlin application
To demonstrate containerizing a Java/Kotlin application we’ll containerize this simple Kotlin web application that can be found on GitHub here https://github.com/minibuildsio/docker-ktor-containerization-example.
The application is a web server that listens on port 8080 and returns some dummy JSON when a GET request is made to /. The entire application is compiled into a single fat jar which is used by Dockerfile below.
# The base image to use this has the Java runtime installed
FROM openjdk:21-slim
# Labels can be used to add metadata to an image
# below is a standard label that provides a link to the source code
LABEL org.opencontainers.image.source= \
https://github.com/minibuildsio/docker-ktor-containerization-example
# Set the working directory
WORKDIR /usr/app/
# Copy the fat jar to the image
COPY build/libs/*-all.jar app.jar
# Expose the port that the application listens on
EXPOSE 8080
# Command to run the application
CMD ["java", "-jar", "app.jar"]
Build the image and tag it with docker-ktor-containerization-example using the -t parameter.
docker build -t docker-ktor-containerization-example .
Run the image using -p [hostPort]:[containerPort] to expose the application running in the container to the host.
docker run -p 8080:8080 docker-ktor-containerization-example
Requests made to http://localhost:8080 will routed to the application running in the container.
Using a builder container to build and containerize a Go application
To demonstrate using a builder container to build and containerize a Go application we’ll containerize this CLI that can be found on GitHub here https://github.com/minibuildsio/moon.
# The base image that contains the Go compiler
FROM golang:alpine AS builder
# Install some dependencies that Go needs
RUN apk update && apk add --no-cache git
WORKDIR $GOPATH/src/
# Copy the source code to the builder
COPY . .
# Build the application and output the binary to /bin/moon
RUN go build -o /bin/moon
### Start of the application image
# Go applications don't require an dependencies
# so can use the minimal scratch base image which is essentially an empty image
FROM scratch
WORKDIR /app
# Copy the binary from the builder to the final application image
COPY --from=builder /bin/moon /bin/moon
# Command to run the application
CMD ["/bin/moon"]
The image can be built and run in the same way as the previous image:
docker build -t moon .
docker run moon