Sign In

  • Username:
  • Password:

Upload File

  •  

Dockerize a Go Application, with Nginx and Databases

Dockerize a Web application gives many benefits.
This post goes over how to deploy a Go application with Nginx and Mariadb using Docker Compose.

0x01 Go & Alpine Linux

In case we only need to ship a binary and some templates, the offical Go image looks like too fat for us.
Luckily, the smallest image Alpine Linux is only 4.15MB in size!
But we need to statically compile our app with all libraries built in.

The build scirpt:

CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o sg-amyang

And the dockerfile is simple:

FROM alpine

ADD templates/ /templates
ADD sg-amyang /

CMD [ "/sg-amyang" ]

0x02 Mariadb

Read the offical doc carefully!
I waste lots of time here…
Just link the db with app, and set the host as the database container’s name, then docker will resolve the ip automatically.
Like this.

services:
  db:
    image: mariadb
    expose:
      - "3306"
    environment:
      - MYSQL_ROOT_PASSWORD=passwd
  app:
    images: alpine
    links:
      - db
    # the db init needs time.
    restart: always
db, err := sql.Open("mysql", "user:passwd@tcp(db:3306)/sg_amyang?charset=utf8")

And here’s a script about backup and restore a mariadb database from a running docker mariadb container.

# Backup
docker exec CONTAINER /usr/bin/mysqldump -u root --password=root DATABASE > backup.sql

# Restore
cat backup.sql | docker exec -i CONTAINER /usr/bin/mysql -u root --password=root DATABASE

0x03 Nginx

nothig special.

0x04 Whole YAML

Here’s the docker-compose.yml for this blog.

version: '3'

services:
  db:
    image: mariadb
    expose:
      - "3306"
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_USER=user
      - MYSQL_PASSWORD=password
      - MYSQL_DATABASE=sg_amyang

  app:
    build: 
      context: ../
      dockerfile: docker/Dockerfile
    ports:
      - "16311:16311"
    depends_on:
      - db
    links:
      - db
    restart:
      always
    environment:
      - DB_Passwd=password
      - SecretKey=biubiubiu
    volumes:
      - ../uploadsfolder:/uploadsfolder

  nginx:
    image: nginx
    ports:
      - "80:80"
      - "443:443"
    depends_on:
      - app
    links:
      - app
    restart:
      always
    volumes:
      - ../static:/static
      - ../uploadsfolder:/uploadsfolder
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./nginx/sites-enabled:/etc/nginx/sites-enabled
      # - /etc/letsencrypt/:/etc/letsencrypt