Prerequisites
To follow this tutorial, you will need the following:- Go
- [Docker] to build standalone containers to serve your Go app.
This guide assumes that you have basic knowledge of the above-mentioned technologies and tools. If you are not
familiar with any of them, it is recommended to review their official documentation and tutorials to get up to speed
before proceeding with this guide.
Go HTTP Server
- Run the command
go mod init go-http-server
to set up your project and manage its dependencies. - Now, create a file named
main.go
and add the following code to set up a basic http server using the gin web framework.
main.go
- Export the required environment variables,
- Run
go mod download
command to download the required dependencies. - Run the command
go run main.go
to start the server.
Dockerize
Dockerizing makes your app run anywhere, agnostic of the platform.Create .dockerignore
Before creating the dockerfile, let’s create a.dockerignore
file and add that contents that should not be copied over
to the docker file system.
.dockerignore
Creating a
.dockerinogre
file and adding folders like node_modules
is must, since dependencies will be installed
while building the image based on the platform preferences used. Copying those from file system will overwrite the
installed dependencies and might fail during deploymentsCreate Dockerfile
Now, Create a Dockerfile. The Dockerfile is a text file that contains the instructions for Docker to build the image. The Dockerfile is posted for reference with steps to create the production image. Though docker supports Multi-Stage Builds we won’t be using that here. In this example we will copysource code
and build and run it inside the container. You can opt for multi stage build, if you want to
build the go binary in build stage and run it in another stage.
Refer to this doc to know more about building docker images
for go applications.
Dockerfile
Build and test docker image
Now you can build and run the Docker image. To build the Docker image:go-http-server
image for platform linux/amd64
.
If you are locally testing your application, you can skip the platform
key to build the images