Introduction to Deploying Go Apps with NGINX and Docker
In this article, you will learn how to deploy Go applications using Docker and NGINX. This combination is a powerful toolset for developers looking to scale applications efficiently while ensuring reliable performance. By following this guide, you will containerize a Go application and set up NGINX as a reverse proxy.
Prerequisites
- Basic knowledge of Go and Docker
- Docker and Docker Compose installed on your system
- NGINX
Step 1: Writing a Sample Go Application
Let's start by creating a simple Go application. For demonstration, we'll build a basic HTTP server.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
This application listens for HTTP requests on port 8080 and responds with "Hello, world!".
Step 2: Dockerizing the Go Application
Create a Dockerfile to build the Go application into a Docker image.
# Start with a base image containing Go
FROM golang:alpine AS builder
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy the source code into the container
COPY . .
# Build the Go application
RUN go build -o main .
# Start a fresh image
FROM alpine
# Copy the executable from the builder stage
COPY --from=builder /app/main ./main
# Command to run the executable
CMD ["./main"]
Step 3: Configuring NGINX
Next, let's configure NGINX to work as a reverse proxy for the Go application. Here's a simple NGINX configuration:
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://go_app:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
This configuration makes NGINX listen on port 80 and forward the traffic to the Go application running on port 8080 within Docker.
Step 4: Using Docker Compose
To manage and link the containers, we use Docker Compose. Create a docker-compose.yml file as follows:
version: '3'
services:
go_app:
build: .
container_name: go_app
restart: always
nginx:
image: nginx
container_name: nginx
restart: always
ports:
- "80:80"
volumes:
- ./your-nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- go_app
Run docker-compose up to start both the Go application and NGINX with the correct configuration. This setup allows you to access the application via http://localhost.
Conclusion
By following the steps in this article, you've successfully containerized a Go application and set it up with NGINX as a reverse proxy in Docker. This setup is a fundamental pattern for deploying scalable web applications, giving you both flexibility and efficiency in hosting Go applications.