Skip to content

Instantly share code, notes, and snippets.

@mciantyre
Created July 9, 2018 19:54
Show Gist options
  • Save mciantyre/0ba89c47e7dff78c28ec613b5c0ee55a to your computer and use it in GitHub Desktop.
Save mciantyre/0ba89c47e7dff78c28ec613b5c0ee55a to your computer and use it in GitHub Desktop.
Nginx proxy to two microservices
# We demonstrate an nginx reverse proxy that can forward along to
# two different microservices, alpha and beta.
#
# Run with 'docker-compose up', then hit one of the two endpoints:
#
# localhost:8080/app1 => alpha service
# localhost:8080/app2 => beta service
#
# The services simply respond with plain text describing the services.
version: '3' # For modern Docker Compose...
services: # Define services here
web: # The web service...
image: nginx # ... uses the publicly available nginx image
volumes: # ... and uses the included nginx.conf for proxy routing
- ./nginx.conf:/etc/nginx/conf.d/default.conf
ports:
- "8080:80" # forward your port 8080 -> internal network's port 80
depends_on: # Don't start until both alpha and beta are up!
- alpha
- beta
alpha: # The alpha service...
build: . # ... is built using the Dockerfile in this directory
environment: # We set this variable, so the service prints out a unique name
- MESSAGE=alpha
beta: # The beta service, same as alpha...
build: .
environment:
- MESSAGE=beta
# Temporary image to coordinate the build...
FROM golang:1.10-alpine
ADD service.go /go/src/service/service.go
RUN go install service
# The actual output image
FROM alpine:latest
COPY --from=0 /go/bin/service .
ENV PORT 8080
CMD ["./service"]
server {
listen 80;
location /app1/ {
proxy_pass http://alpha:8080;
}
location /app2/ {
proxy_pass http://beta:8080;
}
}
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
msg := os.Getenv("MESSAGE")
if "" == msg {
msg = "did not set MESSAGE environment variable"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from %s", msg)
})
log.Printf("Starting service %s", msg)
log.Fatalln(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment