# Production Go API Stack

> Production Go API with Nginx, PostgreSQL, Redis caching, and structured logging

- Category: Full Web Stacks
- Difficulty: advanced
- Components: nginx, go, postgres, redis
- Tags: go, golang, api, production, nginx, postgres, redis
- Source: https://docker.recipes/full-stacks/production-go-api-stack

## Overview

NGINX is a high-performance web server and reverse proxy that has become the backbone of modern web infrastructure, powering over 400 million websites worldwide. Originally developed to solve the C10K problem of handling 10,000 concurrent connections, NGINX uses an event-driven, asynchronous architecture that dramatically outperforms traditional process-based servers under high load conditions.

This production stack combines NGINX's proven reverse proxy capabilities with Go's exceptional performance characteristics for building scalable APIs. The architecture leverages PostgreSQL's ACID compliance and advanced JSON support for reliable data persistence, while Redis provides sub-millisecond caching and session storage. Go's compiled binary approach, combined with NGINX's efficient connection handling, creates a stack capable of serving thousands of concurrent API requests with minimal resource overhead.

This configuration targets engineering teams building high-throughput APIs that need production-grade reliability without the complexity of cloud-native orchestration. The stack excels for fintech applications requiring transaction integrity, e-commerce platforms with high concurrent user loads, and SaaS products where response time directly impacts user experience. The combination of Go's garbage collector optimizations and Redis caching can reduce database load by 80-90% while maintaining data consistency through PostgreSQL's robust transaction system.

## Features

- Event-driven NGINX architecture handles 10,000+ concurrent connections with minimal memory footprint
- Go's compiled binary deployment eliminates runtime dependencies and reduces container size to under 20MB
- PostgreSQL JSONB support enables hybrid relational-document queries with full ACID compliance
- Redis Lua scripting enables atomic rate limiting and complex caching operations in sub-millisecond timeframes
- Multi-stage Docker builds separate development dependencies from production runtime for enhanced security
- Structured logging with Go's context package provides distributed tracing across NGINX, API, and database layers
- PostgreSQL connection pooling through Go's database/sql package optimizes resource utilization under load
- NGINX upstream health checks automatically route traffic away from failed API instances

## Use cases

- E-commerce APIs requiring sub-100ms response times with Redis product catalog caching
- Financial services applications needing PostgreSQL's ACID transactions for payment processing
- Multi-tenant SaaS platforms using PostgreSQL row-level security and Redis session isolation
- Real-time analytics dashboards leveraging PostgreSQL's window functions and Redis pub/sub
- Content management systems utilizing PostgreSQL's full-text search with Redis query result caching
- IoT data ingestion APIs using Go's goroutines for concurrent processing and PostgreSQL time-series storage
- Mobile app backends requiring JWT authentication with Redis token blacklisting and PostgreSQL user management

## Prerequisites

- Minimum 2GB RAM (1GB for PostgreSQL, 512MB for Redis, 256MB for Go API, 256MB for NGINX)
- Docker Engine 20.10+ with BuildKit support for multi-stage Dockerfile optimization
- Available ports 80 (NGINX), 5432 (PostgreSQL), 6379 (Redis), or configure alternatives via environment variables
- Understanding of Go module structure and PostgreSQL migration patterns for application development
- Basic knowledge of NGINX upstream configuration for production load balancing scenarios
- SSL certificate management if deploying with HTTPS termination at NGINX layer

## docker-compose.yml

```yaml
services:
  nginx:
    image: nginx:alpine
    container_name: go-nginx
    restart: unless-stopped
    ports:
      - "${NGINX_PORT:-80}:80"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - api

  api:
    build:
      context: .
      dockerfile: Dockerfile
      target: production
    container_name: go-api
    restart: unless-stopped
    environment:
      - GIN_MODE=release
      - PORT=8080
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}?sslmode=disable
      - REDIS_URL=redis://redis:6379
      - JWT_SECRET=${JWT_SECRET}
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started

  db:
    image: postgres:16-alpine
    container_name: go-db
    restart: unless-stopped
    environment:
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASSWORD}
      - POSTGRES_DB=${DB_NAME}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    container_name: go-redis
    restart: unless-stopped
    command: redis-server --appendonly yes
    volumes:
      - redis_data:/data

  migrate:
    build:
      context: .
      dockerfile: Dockerfile
      target: migrate
    container_name: go-migrate
    environment:
      - DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}?sslmode=disable
    depends_on:
      db:
        condition: service_healthy
    profiles:
      - tools

volumes:
  postgres_data:
  redis_data:
```

## .env

```bash
# Go API Production Stack
NGINX_PORT=80

# Security
JWT_SECRET=your-jwt-secret-key

# Database
DB_USER=goapi
DB_PASSWORD=goapi_password
DB_NAME=goapi_db
```

## Usage notes

- Multi-stage Dockerfile for small production image
- Run migrations: docker compose --profile tools up migrate
- API uses Redis for caching and rate limiting
- Nginx handles SSL termination and load balancing
- Health checks ensure proper startup order
- Binary compiled with CGO_ENABLED=0 for Alpine

## Troubleshooting

- Connection refused on port 80: Check NGINX_PORT environment variable and ensure no conflicts with existing services
- Go API panics with database connection errors: Verify DATABASE_URL format and ensure PostgreSQL health check passes before API startup
- Redis connection timeouts: Increase Redis maxclients setting or implement connection pooling in Go application code
- NGINX 502 Bad Gateway: Confirm Go API is listening on port 8080 and check upstream configuration in nginx.conf
- PostgreSQL migration failures: Run migrations separately using docker compose --profile tools up migrate before starting main services
- High memory usage in Go API: Enable Go's garbage collector debug logging with GOGC environment variable tuning

