Know how to create a Go application, deploy to Heroku (automatically) and configure your domain to point the domain provided by Heroku.
- Use Git and GitHub
- Create a simple Go backend server
- Use Docker
- Use Heroku platform
- DNS configuration
- Go
- Heroku CLI
- Git
- Docker
- Domain (optional)
- Go to www.github.com and click "New"
- Check Add README and Add .gitignore and select Go from the list
git clone git@github.com:<YOUR_USERNAME>/<YOUR_APP>.git
We will write a simple server with single endpoint.
The endpoint will be GET /ping
and it will response a 200 OK
status code and the message "pong"
.
The folder structure will be:
|-cmd
| |-main.go // Contains the entry point
|
|-internal
| |-router
| |-router.go // Contains the router initialization
| |-endpoints.go // Contains all the endpoints
|
|-defines
| |-paths.go // Contains the paths of each endpoint
- Init the module
go mod init <YOUR_APP>
- Download
gin-gonic
librarygo get -u github.com/gin-gonic/gin
- Create a file with name
Dockerfile
in the root of the project with the following content# Use alpine (very lightweight linux distro) with Go installed as a base image FROM golang:rc-alpine3.14 AS builder # Create a folder called build RUN mkdir /build # Change the working directory to the new folder WORKDIR /build # Copy all the contents to the new folder COPY . . # Build binary RUN go build -o output ./cmd/main.go # Use alpine as a base image FROM alpine # Create a user RUN adduser -S -D -H -h /app appuser # Change current user USER appuser # Copy the binary created before to a new folder COPY --from=builder /build/output /app/ # Change the working directory to the new folder WORKDIR /app # Execute the binary CMD ["./output"]
- Build docker image
docker build -t <YOUR_APP> .
- Run the image
docker run --rm -p 8080:8080 <YOUR_APP>
- Go to Heroku Dashboard and click on New > New app
- Go to Deploy tab > Deployment method > Github
- Login with GitHub and search for <YOUR_APP>
- Click on Connect
- Click Enable Automatic Deploys
- Login in Heroku CLI
heroku login
- Set stack to container
heroku stack:set container --app <YOUR_APP>
- Create a file with name
heroku.yml
in the root of the project with the following contentbuild: docker: web: Dockerfile
git add .
git commit -m "Initial version"
git push