» Go: Build a REST API with Gin » 3. Deployment » 3.3 Docker and Docker Compose

Docker and Docker Compose

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/

Dockerfile

A Dockerfile is a text file that contains instructions for building a Docker image. It defines the steps needed to create a Docker image, which serves as a blueprint for launching Docker containers.

Add Dockerfile:

# alpine linux
FROM alpine:3.19

# Prepare server stuff
ENV APP_BIN=lrbooks
ARG SERVER_DIR=/home/.server
WORKDIR $SERVER_DIR
COPY ./${APP_BIN} .

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 a new binary file that's suitable for Linux environment:

make build-linux

It's equivalent to GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o lrbooks.

Build your docker image like this:

docker build . -t lrbooks:latest

Note:
Use sudo docker ... in case you have any permission issue.

Do docker images to check your images:

docker images

Result:

REPOSITORY                 TAG       IMAGE ID       CREATED         SIZE
lrbooks                    latest    6ce922011450   2 minutes ago   34.2MB
...

Docker Compose

Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to use a YAML file to configure your application's services, networks, and volumes, and then spin up all the containers required to run your application with a single command.

Note:
The easiest and recommended way to get Docker Compose is to install Docker Desktop. Docker Desktop includes Docker Compose along with Docker Engine and Docker CLI which are Compose prerequisites.

Install Compose if needed: https://docs.docker.com/compose/install/

Add compose/docker-compose.yml:

services:
  lr-rest-books:
    image: lrbooks:latest
    ports:
      - 8080:8080
    volumes:
      - ./config.yml:/home/.server/config.yml
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_started
      mongo:
        condition: service_started
  redis:
    image: docker.io/bitnami/redis:7.0
    environment:
      - REDIS_PASSWORD=${REDIS_PASSWORD}
    ports:
      - 6379:6379
  mysql:
    image: docker.io/bitnami/mysql:5.7.43
    environment:
      - MYSQL_DATABASE=lr_book
      - MYSQL_USER=test_user
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
    ports:
      - 3306:3306
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      timeout: 20s
      retries: 10
    volumes:
      - ~/lr-mysql-data:/bitnami/mysql/data
  mongo:
    image: bitnami/mongodb:latest
    environment:
      - ALLOW_EMPTY_PASSWORD=yes
    ports:
      - 27017:27017
    volumes:
      - ~/lr-mongodb-data:/bitnami/mongodb

Add compose/config.yml:

app:
  port: 8080
  page_size: 10
  token_secret: "LiteRank_in_Compose"
  token_hours: 72
db:
  file_name: "test.db"
  dsn: "test_user:test_pass@tcp(mysql:3306)/lr_book?charset=utf8mb4&parseTime=True&loc=Local"
  mongo_uri: "mongodb://mongo:27017"
  mongo_db_name: "lr_book"
cache:
  address: redis:6379
  password: test_pass
  db: 0
  timeout: 50

Add compose/.env:

REDIS_PASSWORD=test_pass
MYSQL_PASSWORD=test_pass
MYSQL_ROOT_PASSWORD=test_root_pass

Caution: .env files should be ignored in .gitignore.

Changes in .gitignore:

@@ -22,3 +22,4 @@ go.work
 
 test.db
 lrbooks
+.env

Run it:

cd compose
docker compose up

You should see something like this:

[+] Running 4/4
 ✔ Container compose-mongo-1          Created                                                                                                                                                                                          0.0s 
 ✔ Container compose-redis-1          Created                                                                                                                                                                                          0.0s 
 ✔ Container compose-mysql-1          Recreated                                                                                                                                                                                        0.1s 
 ✔ Container compose-lr-rest-books-1  Recreated                                                                                                                                                                                        0.0s 
Attaching to lr-rest-books-1, mongo-1, mysql-1, redis-1
redis-1          | redis 13:24:52.38 
redis-1          | redis 13:24:52.39 Welcome to the Bitnami redis container
...

mongo-1          | mongodb 13:24:52.60 INFO  ==> 
mongo-1          | mongodb 13:24:52.60 INFO  ==> Welcome to the Bitnami mongodb container
mongo-1          | mongodb 13:24:52.61 INFO  ==> ** Starting MongoDB setup **
...
mysql-1          | mysql 13:24:52.61 
mysql-1          | mysql 13:24:52.62 Welcome to the Bitnami mysql container
mysql-1          | mysql 13:24:52.63 INFO  ==> ** Starting MySQL setup **
...

You don't need to manually install or setup those databases anymore. They're all in good hands with docker compose.

If you send some requests to your api server on port 8080, you should see logs like this as well:

lr-rest-books-1  | [GIN] 2024/02/27 - 13:26:09 | 200 |    2.647982ms |    192.168.65.1 | GET      "/books/1/reviews"
lr-rest-books-1  | [GIN] 2024/02/27 - 13:27:15 | 401 |      51.059µs |    192.168.65.1 | POST     "/books"
lr-rest-books-1  | [GIN] 2024/02/27 - 13:27:15 | 401 |      28.097µs |    192.168.65.1 | POST     "/books"
lr-rest-books-1  | [GIN] 2024/02/27 - 13:27:15 | 401 |      25.604µs |    192.168.65.1 | POST     "/books"
...

If you want to skip the API server’s docker image building step, you may tune the compose/docker-compose.yml:

@@ -1,6 +1,8 @@
 services:
   lr-rest-books:
-    image: lrbooks:latest
+    build:
+      context: ../
+      dockerfile: Dockerfile
     ports:
       - 8080:8080
     volumes:

Run again:

docker compose up

The compose plugin will build the image for you if needed.

[+] Building 3.2s (9/9) FINISHED                                                                                                                                                                                       docker:desktop-linux
 => [lr-rest-books internal] load build definition from Dockerfile                                                                                                                                                                     0.0s
 => => transferring dockerfile: 242B                                                                                                                                                                                                   0.0s
 => [lr-rest-books internal] load metadata for docker.io/library/golang:1.22.0-alpine3.19                                                                                                                                              3.1s
 => [lr-rest-books auth] library/golang:pull token for registry-1.docker.io                                                                                                                                                            0.0s
 => [lr-rest-books internal] load .dockerignore                                                                                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                                                                                                        0.0s
 => [lr-rest-books 1/3] FROM docker.io/library/golang:1.22.0-alpine3.19@sha256:8e96e6cff6a388c2f70f5f662b64120941fcd7d4b89d62fec87520323a316bd9                                                                                        0.0s
 => [lr-rest-books internal] load build context                                                                                                                                                                                        0.0s
 => => transferring context: 31B                                                                                                                                                                                                       0.0s
 => CACHED [lr-rest-books 2/3] WORKDIR /home/.server                                                                                                                                                                                   0.0s
 => CACHED [lr-rest-books 3/3] COPY ./lrbooks .                                                                                                                                                                                        0.0s
 => [lr-rest-books] exporting to image                                                                                                                                                                                                 0.0s
 => => exporting layers                                                                                                                                                                                                                0.0s
 => => writing image sha256:d3fb8b1826bdf8dfe765980ebf2dc754d38c006e64a11feb42c76900d6540ad4                                                                                                                                           0.0s
 => => naming to docker.io/library/compose-lr-rest-books                                                                                                                                                                               0.0s
[+] Running 4/3
 ✔ Container compose-mongo-1          Created                                                                                                                                                                                          0.0s 
 ✔ Container compose-mysql-1          Created                                                                                                                                                                                          0.0s 
 ✔ Container compose-redis-1          Created                                                                                                                                                                                          0.0s 
 ✔ Container compose-lr-rest-books-1  Recreated                                                                                                                                                                                        0.1s 
Attaching to lr-rest-books-1, mongo-1, mysql-1, redis-1
...

Now, you may try all those endpoints with curl. Everything should work even more smoothly than you expected.

Kubernetes

If you want to push your cloud-native solution even further, please try Kubernetes.

It's also known as K8s and is an open-source system for automating deployment, scaling, and management of containerized applications.

You can make a deployment yaml like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: lr-books-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: lr-books
  template:
    metadata:
      labels:
        app: lr-books
    spec:
      containers:
      - name: lr-books-api
        image: lrbooks:latest
        ports:
        - containerPort: 8080

And apply it with this command:

kubectl apply -f lr-books-deployment.yaml
PrevNext