Containerize Go App with Docker
Learn how to use Docker to efficiently package and deploy Go applications , making them flexible and manageable. Here are detailed instructions.
Docker is the most popular containerization technology due to its simplicity and ease of use. Docker takes the pressure off of portability issues during software development and distribution. You can deploy docker containers to most cloud service providers.
Containerizing Go applications with Docker can help you ensure consistent and reliable deployment across different environments. You can deploy Go apps on different environments like development, staging, and production. Docker containers are lightweight and take up less space than traditional virtual machines. This can save you money on hosting and faster deployment.
Simple web server setup in Go
The Go Standard Library contains the packages you need to set up a simple web server.
First, import the http , log and json packages . You would use Go's http package to set up the server and GET (receive) the request endpoint. Log package to log possible errors to your console. The json package to encode the structure to JSON for the API endpoint.
import ( "encoding/json" "log" "net/http" )
You can encode the struct version as JSON to the client as a query validity-based response like so:
type Message struct { Response string `json:"response"` Description string `json:"description"` }
The handler function will return a success message to the client if the request to the endpoint is a GET request .
// dockerTestEndpoint xử lý endpoint API để kiểm tra kết nối Docker func dockerTestEndpoint(writer http.ResponseWriter, request *http.Request) { // Đặt header để hiện nội dung JSON writer.Header().Set("Content-Type," "application/json") // Nếu phương thức truy vấn là GET if request.Method == "GET" { // Đặt code trạng thái phản hồi là 200 OK writer.WriteHeader(http.StatusOK) // Tạo cấu trúc thông báo cho phản hồi thành công message := Message{ Response: "Successful", Description: "You've successfully hit the API endpoint " + "From your Docker Container", } // Mã hóa thông báo dưới dạng JSON và gửi nó đi dưới dạng phản hồi err := json.NewEncoder(writer).Encode(&message) if err != nil { return } } else { // Nếu phương thức truy vấn không phải là GET // Đặt code trạng thái phản hồi là 400 Bad Request writer.WriteHeader(http.StatusBadRequest) // Tạo cấu trúc thông báo cho phản hồi truy vấn xấu message := Message{ Response: "Bad Request", Description: "You've successfully hit the API endpoint From your " + "Docker Container, But you made a bad request", } // Mã hóa thông báo là JSON và gửi nó làm phản hồi err := json.NewEncoder(writer).Encode(&message) if err != nil { return } } }
You set up the handler function in the main function with the route /api/docker/go . The dockerTestEndpoint handler function validates that the request to the handler is a GET request . If it's a GET request, it encodes a Message struct that is initialized to the client based on the state of the request.
Here's how you can attach a handler on a route and set up the server to run on port 8080:
func main() { // Đăng ký hàm handler 'dockerTestEndpoint' // để xử lý truy vấn URL "/api/docker/go". http.HandleFunc("/api/docker/go", dockerTestEndpoint) // Khởi động server HTTP và nghe các truy vấn đến trên cổng 8080. err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatalln("There's an error with the server:", err) } }
The main function is the entry point to the server, listening on port 8080.The HandleFunc method binds the routes on the handler function. The ListenAndServe method starts the server on the specified localhost port 8080.
Start containerizing your Go app with Docker
After installing and setting up Docker, you need a Docker file called Dockerfile to create and build a Docker image for your Go application. You will specify commands for the base image and commands to copy files, add a working directory, and run the application in the Dockerfile.
Run this command in the terminal of the workspace to create the Dockerfile.
touch Dockerfile
You will specify the commands to build the Docker image in the Dockerfile.
If there are any files that you want to separate from the Docker image, you can use the .dockerignore file . .dockerignore files work exactly like .gitignore files .
touch .dockerignore
Next, you will specify the build commands in the Dockerfile to house your applications.
Define commands in Dockerfile
Dockerfiles are customizable based on project specifications. You will define commands to build the base image for application development.
Example content of Dockerfile to build the above web server:
# Dùng ảnh cơ sở Golang FROM golang:latest # Đặt thư mục hoạt động trong container WORKDIR /app # Sao chép toàn bộ file trong thư mục cục bộ vào thư mục đang hoạt động trong container COPY . . # Download các phụ thuộc mô đun Go RUN go mod download # Xây dựng app Go RUN go build -o app # Đặt điểm vào cho ứng dụng ENTRYPOINT ["./app"]
The Dockerfile uses the golang:latest base image to build the application after setting the working directory to /app .
Dockerfile copies files with COPY command and downloads dependencies with RUN command.
The file specifies the build and run operation with the RUN command , and then sets the command to run when the container starts up with the CMD command.
Save the Dockerfile in the same directory as your go.mod and main.go files; then run this command to create Docker image from Dockerfile:
docker build -t GolangTutorial .
The above command will create a Docker image with the golangtutorial tag . You can run a container with this command:
docker run -p 8080:8080 golangtutorial
This command maps port 8080 from the container to port 8080 on the host machine's localhost. You can tell the server to run in a Docker container from the host machine.
Result from sending CURL query to server:
Hope the article is useful to you!
You should read it
- How to Containerize a Nest.js Application Using Docker and Docker Compose
- How to containerize a Rust app with Docker
- How to use Docker Container
- Docker best practices you need to know
- Docker Hub is used by hackers to spread Cryptojacking malware
- 10 Best Docker Alternatives 2022
- 6 reasons to use Docker virtualization software
- How to run Docker on Raspberry Pi
- 5 useful tips to learn Docker in 2018
- How to safely check desktop applications with Docker
- Common commands in Docker
- How to install Docker in Linux
Maybe you are interested
10 Best Docker Alternatives 2023
How to create an effective Docker image for a Python project
How to Install Apache Guacamole via Docker on Ubuntu 22.04
Docker best practices you need to know
How to Containerize a Nest.js Application Using Docker and Docker Compose
How to containerize a Rust app with Docker