Skip to content

Instantly share code, notes, and snippets.

@SoldierCorp
Created January 28, 2019 21:36
Show Gist options
  • Save SoldierCorp/98f04d026677afcad7cb8b14762eba2a to your computer and use it in GitHub Desktop.
Save SoldierCorp/98f04d026677afcad7cb8b14762eba2a to your computer and use it in GitHub Desktop.
Dockerfile to create a small container for Golang
############################
# STEP 1 build executable binary
############################
FROM golang:alpine as builder
# Install git + SSL ca certificates.
# Git is required for fetching the dependencies.
# Ca-certificates is required to call HTTPS endpoints.
RUN apk update && apk add --no-cache git ca-certificates gcc g++ libc-dev && update-ca-certificates
# Create appuser
RUN adduser -D -g '' appuser
COPY . $GOPATH/src/gitlab.com/SoldierCorp/companies-api
WORKDIR $GOPATH/src/gitlab.com/SoldierCorp/companies-api
ENV GO111MODULE=on
COPY go.mod .
COPY go.sum .
# Fetch dependencies.
# Using go mod with go 1.11
RUN go mod download
# Build the binary
RUN GOOS=linux GOARCH=amd64 go build -ldflags="-w -s" -o /go/bin/companies-api .
############################
# STEP 2 build a small image
############################
FROM scratch
# Import from builder.
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /etc/passwd /etc/passwd
# Copy our static executable
COPY --from=builder /go/bin/companies-api /go/bin/companies-api
# Use an unprivileged user.
USER appuser
# Run the companies-api binary.
ENTRYPOINT ["/go/bin/companies-api"]
# CMD ["/go/bin/companies-api"]
@SoldierCorp
Copy link
Author

SoldierCorp commented Jan 29, 2019

If I add the environment variables directly in the Dockerfile, the app will continue running but I do prefer to use the .env.

So, with the env vars added to the Docker file, now I have this u.u


2019/01/29 04:43:10 GET /api/*/companies/*/
2019/01/29 04:43:10 GET /api/*/companies/*/{slug:^[a-z0-9-]+$}/*/
2019/01/29 04:43:10 GET /api/*/home-slider/*/
2019/01/29 04:43:10 GET /api/*/zones/*/
2019/01/29 04:43:10 listen tcp :80: bind: permission denied

I thought by adding EXPOSE 3000 and using the command docker run -d -p 3000:3000 companies-api will it works but is still showing the same error.

@chemidy
Copy link

chemidy commented Jan 29, 2019

The API is started with unprivileged user appuser : check the following line in dockerfile

USER appuser

If you want to start the API on port 80, just remove this line.

@SoldierCorp
Copy link
Author

Great, now it's working!

I still have the issue with the .env file but since I have an alternative, is not a problem for now.

Thank you so much @chemidy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment