» Go: Building Event-Driven Microservices with Kafka » 5. Deployment » 5.1 Dockerfile

Dockerfile

Docker allows developers to package their applications along with all dependencies into a single unit called a container. This ensures consistency across different environments, such as development, testing, and production, reducing the "it works on my machine" problem.

Install Docker: https://docs.docker.com/engine/install/

Add Makefile

A Makefile is a special file used in software development projects, particularly in Unix-like operating systems, to automate the compilation and building of executable programs or libraries from source code.

Add Makefile:

TARGET_BIN=./bin/
# Binary names
BINARY_WEB=lrbooks_web
BINARY_TREND=lrbooks_trend
BINARY_REC=lrbooks_rec

build-web:
	@echo "Building $(BINARY_WEB) for Linux..."
	GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ${TARGET_BIN}$(BINARY_WEB) service/web/main.go

build-trend:
	@echo "Building $(BINARY_TREND) for Linux..."
	GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ${TARGET_BIN}$(BINARY_TREND) service/trend/main.go

build-rec:
	@echo "Building $(BINARY_REC) for Linux..."
	GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ${TARGET_BIN}$(BINARY_REC) service/recommendation/main.go

build: build-web build-trend build-rec

We‘re building for Linux because these binaries will be deployed in a Linux environment inside Docker.

Run make build to build all binaries:

make build

Dockerfile for the web service

Add service/web/Dockerfile:

# alpine linux
FROM alpine:3.19

ENV APP_BIN=lrbooks_web
ARG SERVER_DIR=/home/.server
WORKDIR $SERVER_DIR
COPY ./bin/${APP_BIN} .
COPY ./service/web/adapter/templates/ ./templates

ENV GIN_MODE=release

CMD ./${APP_BIN}

Alpine Linux is a lightweight and secure Linux distribution that is particularly well-suited for containerized environments, embedded systems, and resource-constrained environments where efficiency and security are paramount.

Build the docker image for the web service:

docker build -t lrbooks_web:latest -f service/web/Dockerfile .

Similarly, add 2 more Dockerfiles:

Dockerfile for the trend service

Add service/trend/Dockerfile:

# alpine linux
FROM alpine:3.19

ENV APP_BIN=lrbooks_trend
ARG SERVER_DIR=/home/.server
WORKDIR $SERVER_DIR
COPY ./bin/${APP_BIN} .

ENV GIN_MODE=release

CMD ./${APP_BIN}

Dockerfile for the recommendation service

Add service/recommendation/Dockerfile:

# alpine linux
FROM alpine:3.19

ENV APP_BIN=lrbooks_rec
ARG SERVER_DIR=/home/.server
WORKDIR $SERVER_DIR
COPY ./bin/${APP_BIN} .

ENV GIN_MODE=release

CMD ./${APP_BIN}

With all the Dockerfiles, we‘re well prepared to run them all together in the Docker Compose.

PrevNext