Containerizing the application is very popular nowadays and it makes the deployment so easy. This post will show how to create a Dockerfile for golang application. There are basically two steps in the Dockerfile:
- Build the golang program source code
- Containerize the golang app binary
# Build source code
FROM golang:1.18-alpine AS build
WORKDIR /go/src/github.com/app
COPY . .
RUN go mod tidy
RUN CGO_ENABLED=0 GOOS=linux go build -a -o main .
# Containerize the binary
FROM alpine
COPY --from=build /go/src/github.com/app/main .
EXPOSE 3500
CMD ["/main"]
Exporting the port 3500
is because golang app listens to 3500
. Here is just an example.
If you need to start up the app docker image with environment variables, you can add line 16-19 into the dockerfile.
# Build source code
FROM golang:1.18-alpine AS build
WORKDIR /go/src/github.com/app
COPY . .
RUN go mod tidy
RUN CGO_ENABLED=0 GOOS=linux go build -a -o main .
# Containerize the binary
FROM alpine
COPY --from=build /go/src/github.com/app/main .
ARG service_username
ARG service_password
ENV SERVICE_USERNAME=${service_username}
ENV SERVICE_PASSWORD=${service_password}
EXPOSE 3500
CMD ["/main"]
After finishing the Dockerfile, the rest will be very easy. You’ll just need to build the docker image based on the Dockerfile and run or push it to the image registry.
docker build -t app:0.0.1 -f Dockerfile .
docker image push app:0.0.1
# Or
docker run -it -p 3500:3500 app:0.0.1
If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!