Skip to main content

Dockerfile Basics

Dockerfile to automate

Create a file Dockerfile with the sample content below and also .dockerignore to give directives to ignore or consider certain files during the build process. General guidelines and best practices can found on docker site. guidelines

ref: golang Dockerfile reference

# golang base image with version 1.22
FROM golang:1.22

# current working directory
WORKDIR /usr/src/app

# pre-copy/cache go.mod for pre-downloading dependencies and only redownloading them in subsequent builds if they change
COPY go.mod go.sum ./
RUN go mod download && go mod verify

# copy the content of the current directory to the WORKDIR of the image
COPY . .
RUN go build -v -o /usr/local/bin/app ./...

# exposes the 9000 port as the app requires to communicate
EXPOSE 9000

# CMD is used to start the app
CMD ["app"]

Building image with Dockerfile

build image

docker build -t my-golang-app .
  • -t tag the image and . (dot) is needed to specify the current directory

run the image interactive mode

docker run -it --rm --name my-running-app my-golang-app

my-running-app is the container and my-golang-app is the app which is generated.

interact with the container - exec

docker exec -it <container-name> /bin/bash

ports and env

To map the port use option -p and environment variables -e options

docker run -p 9001:9000 -e DATABASE_URL="postgres://avnadmin:somepasswordlsjdflsdjfdsljf:25579/defaultdb?sslmode=require" my-golang-app