RuleStack

Configs

Stacks

Compare

Diff

RuleStack

Configs

Stacks

Compare

Diff

Read API

RuleStack

Configs

Stacks

Compare

Diff

Read API

Configs/Cursor rules/madebyaris/poinf-of-sales

Cursor rule

.cursor/rules/docker-deployment.mdc

Complete Docker containerization, production deployment, and monitoring patterns for POS System

Cursor rules

Quality

77/100

Scores the file, not the repository.

Length

2,890 words

111 headings · 29 code blocks

Repository

118

— · pushed 339 days ago

Last changed

3 days ago

First indexed 3 days ago.
madebyaris/poinf-of-sales/.cursor/rules/docker-deployment.mdcRawGitHub
1---
2globs: Dockerfile,Dockerfile.*,docker-compose.*,*.sh,nginx.conf,.github/workflows/*,k8s/*,*.yml,*.yaml
3description: Complete Docker containerization, production deployment, and monitoring patterns for POS System
4---
5 
6# 🐳 Docker & Production Deployment Guide
7 
8## Container Architecture
9 
10### Service Overview
11The POS system uses a multi-container architecture defined in [docker-compose.yml](mdc:docker-compose.yml):
12 
131. **postgres** - PostgreSQL database with persistent storage
142. **backend** - Golang API server with database connectivity
153. **frontend** - React application served via Nginx
16 
17### Container Networking
18All services communicate through the `pos-network` bridge network:
19- Frontend → Backend: HTTP API calls
20- Backend → Database: PostgreSQL connection
21- External access via exposed ports
22 
23## Development vs Production
24 
25### Development Configuration
26Use [docker-compose.dev.yml](mdc:docker-compose.dev.yml) for development:
27```bash
28docker-compose -f docker-compose.dev.yml up
29```
30 
31**Development Features:**
32- Volume mounts for live code reloading
33- Development-specific environment variables
34- Hot reloading for both frontend (Vite) and backend (Air)
35- Debug logging enabled
36 
37### Production Configuration
38Use [docker-compose.yml](mdc:docker-compose.yml) for production:
39```bash
40docker-compose up -d
41```
42 
43**Production Features:**
44- Optimized multi-stage builds
45- Minimal runtime containers (Alpine-based)
46- Health checks and restart policies
47- Production-ready Nginx configuration
48 
49## Dockerfile Patterns
50 
51### Backend Dockerfile
52Multi-stage build pattern in [backend/Dockerfile](mdc:backend/Dockerfile):
53 
54```dockerfile
55# Build stage - full Go toolchain
56FROM golang:1.21-alpine AS builder
57WORKDIR /app
58COPY go.mod go.sum ./
59RUN go mod download
60COPY . .
61RUN CGO_ENABLED=0 GOOS=linux go build -o main .
62 
63# Production stage - minimal runtime
64FROM alpine:latest
65RUN apk --no-cache add ca-certificates
66WORKDIR /root/
67COPY --from=builder /app/main .
68EXPOSE 8080
69CMD ["./main"]
70```
71 
72### Frontend Dockerfile
73Node.js build with Nginx serving in [frontend/Dockerfile](mdc:frontend/Dockerfile):
74 
75```dockerfile
76# Build stage
77FROM node:18-alpine AS builder
78WORKDIR /app
79COPY package*.json ./
80RUN npm ci --only=production
81COPY . .
82RUN npm run build
83 
84# Production stage - Nginx
85FROM nginx:alpine AS production
86COPY nginx.conf /etc/nginx/nginx.conf
87COPY --from=builder /app/dist /usr/share/nginx/html
88EXPOSE 3000
89CMD ["nginx", "-g", "daemon off;"]
90```
91 
92## Environment Configuration
93 
94### Environment Variables
95Define environment variables in `.env` file or through Docker Compose:
96 
97```env
98# Database
99DB_HOST=postgres
100DB_PORT=5432
101DB_USER=postgres
102DB_PASSWORD=postgres123
103DB_NAME=pos_system
104 
105# Backend
106PORT=8080
107GIN_MODE=release
108 
109# Frontend
110VITE_API_URL=http://localhost:8080
111```
112 
113### Security Considerations
114- Use Docker secrets for sensitive data in production
115- Avoid hardcoding credentials in Dockerfiles
116- Use separate environment files for different stages
117- Rotate passwords and API keys regularly
118 
119## Volume Management
120 
121### Persistent Data Storage
122Database data persists using named volumes:
123```yaml
124volumes:
125 postgres_data:
126 driver: local
127
128services:
129 postgres:
130 volumes:
131 - postgres_data:/var/lib/postgresql/data
132```
133 
134### Development Volume Mounts
135Mount source code for hot reloading in development:
136```yaml
137services:
138 backend:
139 volumes:
140 - ./backend:/app
141 frontend:
142 volumes:
143 - ./frontend:/app
144 - /app/node_modules # Anonymous volume for node_modules
145```
146 
147## Nginx Configuration
148 
149### Reverse Proxy Setup
150Nginx configuration in [frontend/nginx.conf](mdc:frontend/nginx.conf):
151 
152```nginx
153# API proxy to backend
154location /api {
155 proxy_pass http://backend:8080;
156 proxy_set_header Host $host;
157 proxy_set_header X-Real-IP $remote_addr;
158 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
159}
160 
161# SPA routing for React
162location / {
163 try_files $uri $uri/ /index.html;
164}
165```
166 
167### Performance Optimization
168- Gzip compression for static assets
169- Proper caching headers for assets
170- Security headers (CORS, XSS protection)
171- Health check endpoint for load balancers
172 
173## Health Checks & Monitoring
174 
175### Container Health Checks
176Define health checks in Docker Compose:
177```yaml
178services:
179 backend:
180 healthcheck:
181 test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
182 interval: 30s
183 timeout: 10s
184 retries: 3
185 start_period: 40s
186
187 frontend:
188 healthcheck:
189 test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
190 interval: 30s
191 timeout: 3s
192 retries: 3
193```
194 
195### Restart Policies
196Configure appropriate restart policies:
197```yaml
198services:
199 postgres:
200 restart: unless-stopped
201 backend:
202 restart: unless-stopped
203 frontend:
204 restart: unless-stopped
205```
206 
207## Database Initialization
208 
209### Schema & Seed Data
210Database automatically initializes using scripts in [database/init/](mdc:database/init/):
211- [01_schema.sql](mdc:database/init/01_schema.sql) - Table structure and indexes
212- [02_seed_data.sql](mdc:database/init/02_seed_data.sql) - Sample data for development
213 
214### Backup Strategies
215```bash
216# Create database backup
217docker exec pos-postgres pg_dump -U postgres pos_system > backup.sql
218 
219# Restore database
220docker exec -i pos-postgres psql -U postgres pos_system < backup.sql
221```
222 
223## Development Workflow
224Use the comprehensive [Makefile](mdc:Makefile) for all operations:
225```bash
226# Essential commands
227make dev # Start development environment
228make up # Start containers in background
229make down # Stop all containers
230make status # Check service status
231```
232 
233### Database Operations
234```bash
235# Interactive database management
236make create-admin # Create super admin user
237make backup # Backup database and files
238make restore # Restore from backup
239make db-shell # Access PostgreSQL shell
240make db-reset # Reset with fresh data
241```
242 
243### Legacy Commands (use Makefile instead)
244```bash
245# Start all services (legacy)
246docker-compose up -d
247 
248# View logs (use: make logs)
249docker-compose logs -f backend
250 
251# Stop services (use: make down)
252docker-compose down
253 
254# Rebuild containers (use: make rebuild)
255docker-compose up --build
256```
257 
258## Production Deployment
259 
260### Container Registry
261Build and push images for production deployment:
262```bash
263# Build images
264docker build -t pos-backend:latest ./backend
265docker build -t pos-frontend:latest ./frontend
266 
267# Tag for registry
268docker tag pos-backend:latest your-registry/pos-backend:v1.0.0
269docker tag pos-frontend:latest your-registry/pos-frontend:v1.0.0
270 
271# Push to registry
272docker push your-registry/pos-backend:v1.0.0
273docker push your-registry/pos-frontend:v1.0.0
274```
275 
276### Deployment Checklist
277- [ ] Environment variables configured
278- [ ] SSL/TLS certificates installed
279- [ ] Database backups scheduled
280- [ ] Monitoring and logging configured
281- [ ] Security scanning completed
282- [ ] Load balancer configured (if needed)
283- [ ] Domain name and DNS configured
284 
285## Security Best Practices
286 
287### Container Security
288- Use non-root users in containers where possible
289- Keep base images updated
290- Scan images for vulnerabilities
291- Minimize attack surface (minimal base images)
292- Use specific image tags, avoid 'latest'
293 
294### Network Security
295- Use internal networks for service communication
296- Expose only necessary ports
297- Implement proper firewall rules
298- Use HTTPS/TLS for external communication
299 
300## Performance Optimization
301 
302### Build Optimization
303- Use multi-stage builds to reduce image size
304- Leverage Docker build cache effectively
305- Use .dockerignore to exclude unnecessary files
306- Optimize layer ordering for better caching
307 
308### Runtime Optimization
309- Set appropriate resource limits (CPU, memory)
310- Use init systems for proper signal handling
311- Configure log rotation to prevent disk space issues
312- Monitor resource usage and adjust limits accordingly
313 
314## Troubleshooting
315 
316### Common Issues
3171. **Port conflicts** - Ensure ports 3000, 8080, 5432 are available
3182. **Volume permissions** - Check file permissions for mounted volumes
3193. **Network connectivity** - Verify service communication within Docker network
3204. **Environment variables** - Validate all required env vars are set
3215. **Database connection** - Wait for database to be ready before starting backend
322 
323### Debugging Commands
324```bash
325# Check container logs
326docker-compose logs [service-name]
327 
328# Execute commands in container
329docker-compose exec backend sh
330docker-compose exec postgres psql -U postgres pos_system
331 
332# Check network connectivity
333docker-compose exec backend wget -qO- http://postgres:5432
334 
335# Inspect container details
336docker inspect pos-backend
337```
338 
339## 🚀 Production Deployment Strategies
340 
341### Container Registry Best Practices
342```bash
343# ✅ CORRECT: Multi-architecture builds for production
344docker buildx create --name pos-builder --use
345docker buildx build --platform linux/amd64,linux/arm64 -t pos-backend:latest ./backend --push
346 
347# ✅ CORRECT: Semantic versioning for releases
348docker build -t pos-backend:1.2.3 ./backend
349docker build -t pos-backend:latest ./backend
350 
351# Security scanning before deployment
352docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
353 aquasec/trivy image pos-backend:1.2.3
354```
355 
356### Production Docker Compose
357```yaml
358# docker-compose.prod.yml - Production configuration
359version: '3.8'
360
361services:
362 postgres:
363 image: postgres:15-alpine
364 environment:
365 POSTGRES_DB: ${DB_NAME}
366 POSTGRES_USER: ${DB_USER}
367 POSTGRES_PASSWORD_FILE: /run/secrets/db_password
368 PGDATA: /var/lib/postgresql/data/pgdata
369 volumes:
370 - postgres_data:/var/lib/postgresql/data
371 - ./database/init:/docker-entrypoint-initdb.d
372 secrets:
373 - db_password
374 healthcheck:
375 test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d ${DB_NAME}"]
376 interval: 10s
377 timeout: 5s
378 retries: 5
379 start_period: 30s
380 restart: unless-stopped
381
382 backend:
383 image: your-registry/pos-backend:${VERSION}
384 environment:
385 DB_HOST: postgres
386 DB_PORT: 5432
387 DB_USER: ${DB_USER}
388 DB_PASSWORD_FILE: /run/secrets/db_password
389 JWT_SECRET_FILE: /run/secrets/jwt_secret
390 GIN_MODE: release
391 secrets:
392 - db_password
393 - jwt_secret
394 depends_on:
395 postgres:
396 condition: service_healthy
397 healthcheck:
398 test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/health"]
399 interval: 30s
400 timeout: 10s
401 retries: 3
402 start_period: 40s
403 restart: unless-stopped
404 deploy:
405 resources:
406 limits:
407 memory: 512M
408 cpus: '0.5'
409 reservations:
410 memory: 256M
411 cpus: '0.25'
412
413 frontend:
414 image: your-registry/pos-frontend:${VERSION}
415 environment:
416 VITE_API_URL: ${API_URL}
417 depends_on:
418 backend:
419 condition: service_healthy
420 healthcheck:
421 test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:80"]
422 interval: 30s
423 timeout: 3s
424 retries: 3
425 restart: unless-stopped
426 ports:
427 - "80:80"
428 - "443:443"
429 deploy:
430 resources:
431 limits:
432 memory: 128M
433 cpus: '0.25'
434
435secrets:
436 db_password:
437 external: true
438 name: pos_db_password
439 jwt_secret:
440 external: true
441 name: pos_jwt_secret
442
443volumes:
444 postgres_data:
445 driver: local
446
447networks:
448 default:
449 driver: overlay
450 attachable: true
451```
452 
453### Docker Secrets Management
454```bash
455# ✅ CORRECT: Create production secrets
456echo "your-strong-db-password" | docker secret create pos_db_password -
457echo "your-jwt-secret-key-256-bits-long" | docker secret create pos_jwt_secret -
458 
459# Deploy with secrets
460docker stack deploy -c docker-compose.prod.yml pos-system
461 
462# Rotate secrets (zero downtime)
463echo "new-password" | docker secret create pos_db_password_v2 -
464# Update compose file to use new secret
465docker stack deploy -c docker-compose.prod.yml pos-system
466docker secret rm pos_db_password
467```
468 
469## 🏗️ CI/CD Pipeline Patterns
470 
471### GitHub Actions Workflow
472```yaml
473# .github/workflows/deploy.yml
474name: Build and Deploy POS System
475
476on:
477 push:
478 branches: [ main ]
479 pull_request:
480 branches: [ main ]
481
482env:
483 REGISTRY: ghcr.io
484 IMAGE_BASE: ${{ github.repository }}
485
486jobs:
487 test:
488 runs-on: ubuntu-latest
489 services:
490 postgres:
491 image: postgres:15
492 env:
493 POSTGRES_PASSWORD: postgres
494 POSTGRES_DB: pos_test
495 options: >-
496 --health-cmd pg_isready
497 --health-interval 10s
498 --health-timeout 5s
499 --health-retries 5
500
501 steps:
502 - uses: actions/checkout@v4
503
504 - name: Set up Go
505 uses: actions/setup-go@v4
506 with:
507 go-version: '1.21'
508
509 - name: Set up Node.js
510 uses: actions/setup-node@v4
511 with:
512 node-version: '18'
513 cache: 'npm'
514 cache-dependency-path: frontend/package-lock.json
515
516 - name: Run backend tests
517 run: |
518 cd backend
519 go test -v -race -coverprofile=coverage.out ./...
520 go tool cover -html=coverage.out -o coverage.html
521
522 - name: Run frontend tests
523 run: |
524 cd frontend
525 npm ci
526 npm run test:coverage
527
528 - name: Upload coverage to Codecov
529 uses: codecov/codecov-action@v3
530
531 security:
532 runs-on: ubuntu-latest
533 steps:
534 - uses: actions/checkout@v4
535
536 - name: Run Trivy vulnerability scanner
537 uses: aquasecurity/trivy-action@master
538 with:
539 scan-type: 'fs'
540 scan-ref: '.'
541 format: 'sarif'
542 output: 'trivy-results.sarif'
543
544 - name: Upload Trivy scan results to GitHub Security tab
545 uses: github/codeql-action/upload-sarif@v2
546 with:
547 sarif_file: 'trivy-results.sarif'
548
549 build:
550 needs: [test, security]
551 runs-on: ubuntu-latest
552 outputs:
553 backend-image: ${{ steps.meta-backend.outputs.tags }}
554 frontend-image: ${{ steps.meta-frontend.outputs.tags }}
555
556 steps:
557 - uses: actions/checkout@v4
558
559 - name: Set up Docker Buildx
560 uses: docker/setup-buildx-action@v3
561
562 - name: Login to Container Registry
563 uses: docker/login-action@v3
564 with:
565 registry: ${{ env.REGISTRY }}
566 username: ${{ github.actor }}
567 password: ${{ secrets.GITHUB_TOKEN }}
568
569 - name: Extract backend metadata
570 id: meta-backend
571 uses: docker/metadata-action@v5
572 with:
573 images: ${{ env.REGISTRY }}/${{ env.IMAGE_BASE }}/backend
574 tags: |
575 type=ref,event=branch
576 type=ref,event=pr
577 type=sha,prefix={{branch}}-
578 type=raw,value=latest,enable={{is_default_branch}}
579
580 - name: Build and push backend
581 uses: docker/build-push-action@v5
582 with:
583 context: ./backend
584 platforms: linux/amd64,linux/arm64
585 push: true
586 tags: ${{ steps.meta-backend.outputs.tags }}
587 labels: ${{ steps.meta-backend.outputs.labels }}
588 cache-from: type=gha
589 cache-to: type=gha,mode=max
590
591 - name: Extract frontend metadata
592 id: meta-frontend
593 uses: docker/metadata-action@v5
594 with:
595 images: ${{ env.REGISTRY }}/${{ env.IMAGE_BASE }}/frontend
596 tags: |
597 type=ref,event=branch
598 type=ref,event=pr
599 type=sha,prefix={{branch}}-
600 type=raw,value=latest,enable={{is_default_branch}}
601
602 - name: Build and push frontend
603 uses: docker/build-push-action@v5
604 with:
605 context: ./frontend
606 platforms: linux/amd64,linux/arm64
607 push: true
608 tags: ${{ steps.meta-frontend.outputs.tags }}
609 labels: ${{ steps.meta-frontend.outputs.labels }}
610 cache-from: type=gha
611 cache-to: type=gha,mode=max
612
613 deploy:
614 needs: build
615 runs-on: ubuntu-latest
616 if: github.ref == 'refs/heads/main'
617 environment: production
618
619 steps:
620 - uses: actions/checkout@v4
621
622 - name: Deploy to production
623 run: |
624 # Replace with your deployment method (SSH, K8s, etc.)
625 echo "Deploying POS System to production..."
626 echo "Backend: ${{ needs.build.outputs.backend-image }}"
627 echo "Frontend: ${{ needs.build.outputs.frontend-image }}"
628```
629 
630## 📊 Monitoring & Observability
631 
632### Prometheus Monitoring Setup
633```yaml
634# monitoring/docker-compose.monitoring.yml
635version: '3.8'
636
637services:
638 prometheus:
639 image: prom/prometheus:latest
640 container_name: pos-prometheus
641 command:
642 - '--config.file=/etc/prometheus/prometheus.yml'
643 - '--storage.tsdb.path=/prometheus'
644 - '--web.console.libraries=/etc/prometheus/console_libraries'
645 - '--web.console.templates=/etc/prometheus/consoles'
646 - '--storage.tsdb.retention.time=200h'
647 - '--web.enable-lifecycle'
648 ports:
649 - "9090:9090"
650 volumes:
651 - ./prometheus.yml:/etc/prometheus/prometheus.yml
652 - prometheus_data:/prometheus
653 restart: unless-stopped
654
655 grafana:
656 image: grafana/grafana:latest
657 container_name: pos-grafana
658 ports:
659 - "3001:3000"
660 environment:
661 - GF_SECURITY_ADMIN_USER=admin
662 - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD}
663 - GF_USERS_ALLOW_SIGN_UP=false
664 volumes:
665 - grafana_data:/var/lib/grafana
666 - ./grafana/provisioning:/etc/grafana/provisioning
667 - ./grafana/dashboards:/var/lib/grafana/dashboards
668 restart: unless-stopped
669
670 node-exporter:
671 image: prom/node-exporter:latest
672 container_name: pos-node-exporter
673 command:
674 - '--path.procfs=/host/proc'
675 - '--path.rootfs=/rootfs'
676 - '--path.sysfs=/host/sys'
677 - '--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)'
678 ports:
679 - "9100:9100"
680 volumes:
681 - /proc:/host/proc:ro
682 - /sys:/host/sys:ro
683 - /:/rootfs:ro
684 restart: unless-stopped
685
686 postgres-exporter:
687 image: prometheuscommunity/postgres-exporter:latest
688 container_name: pos-postgres-exporter
689 environment:
690 DATA_SOURCE_NAME: "postgresql://${DB_USER}:${DB_PASSWORD}@postgres:5432/${DB_NAME}?sslmode=disable"
691 ports:
692 - "9187:9187"
693 restart: unless-stopped
694
695 cadvisor:
696 image: gcr.io/cadvisor/cadvisor:latest
697 container_name: pos-cadvisor
698 ports:
699 - "8080:8080"
700 volumes:
701 - /:/rootfs:ro
702 - /var/run:/var/run:ro
703 - /sys:/sys:ro
704 - /var/lib/docker/:/var/lib/docker:ro
705 - /dev/disk/:/dev/disk:ro
706 privileged: true
707 devices:
708 - /dev/kmsg
709 restart: unless-stopped
710
711volumes:
712 prometheus_data:
713 grafana_data:
714```
715 
716### Application Metrics in Go Backend
717```go
718// metrics/metrics.go
719package metrics
720 
721import (
722 "github.com/prometheus/client_golang/prometheus"
723 "github.com/prometheus/client_golang/prometheus/promauto"
724)
725 
726var (
727 OrdersCreated = promauto.NewCounterVec(
728 prometheus.CounterOpts{
729 Name: "pos_orders_created_total",
730 Help: "Total number of orders created",
731 },
732 []string{"order_type", "user_role"},
733 )
734 
735 PaymentProcessed = promauto.NewCounterVec(
736 prometheus.CounterOpts{
737 Name: "pos_payments_processed_total",
738 Help: "Total number of payments processed",
739 },
740 []string{"payment_method", "status"},
741 )
742 
743 DatabaseQueries = promauto.NewHistogramVec(
744 prometheus.HistogramOpts{
745 Name: "pos_database_query_duration_seconds",
746 Help: "Database query duration",
747 Buckets: prometheus.DefBuckets,
748 },
749 []string{"query_type"},
750 )
751 
752 HTTPRequestDuration = promauto.NewHistogramVec(
753 prometheus.HistogramOpts{
754 Name: "pos_http_request_duration_seconds",
755 Help: "HTTP request duration",
756 Buckets: prometheus.DefBuckets,
757 },
758 []string{"method", "path", "status_code"},
759 )
760)
761 
762// Middleware for HTTP request metrics
763func PrometheusMiddleware() gin.HandlerFunc {
764 return gin.HandlerFunc(func(c *gin.Context) {
765 start := time.Now()
766
767 c.Next()
768
769 duration := time.Since(start).Seconds()
770 status := strconv.Itoa(c.Writer.Status())
771
772 HTTPRequestDuration.WithLabelValues(
773 c.Request.Method,
774 c.Request.URL.Path,
775 status,
776 ).Observe(duration)
777 })
778}
779```
780 
781### Logging Configuration
782```go
783// logging/logger.go
784package logging
785 
786import (
787 "os"
788 "github.com/sirupsen/logrus"
789 "github.com/gin-gonic/gin"
790)
791 
792func SetupLogger() *logrus.Logger {
793 logger := logrus.New()
794
795 // JSON logging for production
796 if gin.Mode() == gin.ReleaseMode {
797 logger.SetFormatter(&logrus.JSONFormatter{
798 TimestampFormat: "2006-01-02T15:04:05.999Z07:00",
799 })
800 logger.SetLevel(logrus.InfoLevel)
801 } else {
802 logger.SetFormatter(&logrus.TextFormatter{
803 FullTimestamp: true,
804 })
805 logger.SetLevel(logrus.DebugLevel)
806 }
807
808 logger.SetOutput(os.Stdout)
809 return logger
810}
811 
812// Structured logging middleware
813func LoggingMiddleware(logger *logrus.Logger) gin.HandlerFunc {
814 return gin.HandlerFunc(func(c *gin.Context) {
815 start := time.Now()
816
817 c.Next()
818
819 logger.WithFields(logrus.Fields{
820 "method": c.Request.Method,
821 "path": c.Request.URL.Path,
822 "status": c.Writer.Status(),
823 "duration": time.Since(start),
824 "ip": c.ClientIP(),
825 "user_agent": c.Request.UserAgent(),
826 "user_id": c.GetString("user_id"),
827 }).Info("HTTP Request")
828 })
829}
830```
831 
832## 🔒 Production Security Hardening
833 
834### Enhanced Dockerfile Security
835```dockerfile
836# Secure Golang Dockerfile
837FROM golang:1.21-alpine AS builder
838 
839# Create non-root user for build
840RUN addgroup -g 1001 -S appgroup && \
841 adduser -S appuser -u 1001 -G appgroup
842 
843# Install security updates
844RUN apk update && apk upgrade && apk add --no-cache ca-certificates git
845 
846WORKDIR /app
847COPY go.mod go.sum ./
848RUN go mod download && go mod verify
849 
850COPY . .
851 
852# Build with security flags
853RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
854 go build -ldflags='-w -s -extldflags "-static"' -o main .
855 
856# Production stage with minimal attack surface
857FROM alpine:3.18
858 
859# Security updates and minimal tools
860RUN apk update && apk upgrade && \
861 apk add --no-cache ca-certificates && \
862 rm -rf /var/cache/apk/*
863 
864# Create non-root user
865RUN addgroup -g 1001 -S appgroup && \
866 adduser -S appuser -u 1001 -G appgroup
867 
868# Set up app directory
869WORKDIR /app
870COPY --from=builder --chown=appuser:appgroup /app/main .
871 
872# Switch to non-root user
873USER appuser
874 
875# Health check
876HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
877 CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
878 
879EXPOSE 8080
880CMD ["./main"]
881```
882 
883### Nginx Security Configuration
884```nginx
885# nginx.conf - Production security hardening
886user nginx;
887worker_processes auto;
888pid /var/run/nginx.pid;
889 
890events {
891 worker_connections 1024;
892 use epoll;
893 multi_accept on;
894}
895 
896http {
897 # Security headers
898 add_header X-Frame-Options "SAMEORIGIN" always;
899 add_header X-Content-Type-Options "nosniff" always;
900 add_header X-XSS-Protection "1; mode=block" always;
901 add_header Referrer-Policy "no-referrer-when-downgrade" always;
902 add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';" always;
903
904 # Hide server version
905 server_tokens off;
906
907 # Rate limiting
908 limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
909 limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
910
911 # SSL Configuration (when using HTTPS)
912 ssl_protocols TLSv1.2 TLSv1.3;
913 ssl_prefer_server_ciphers on;
914 ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
915
916 # Gzip compression
917 gzip on;
918 gzip_vary on;
919 gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;
920
921 server {
922 listen 80;
923 server_name localhost;
924 root /usr/share/nginx/html;
925 index index.html;
926
927 # API proxy with rate limiting
928 location /api/v1/auth/login {
929 limit_req zone=login burst=3 nodelay;
930 proxy_pass http://backend:8080;
931 proxy_set_header Host $host;
932 proxy_set_header X-Real-IP $remote_addr;
933 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
934 proxy_set_header X-Forwarded-Proto $scheme;
935 }
936
937 location /api/ {
938 limit_req zone=api burst=20 nodelay;
939 proxy_pass http://backend:8080;
940 proxy_set_header Host $host;
941 proxy_set_header X-Real-IP $remote_addr;
942 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
943 proxy_set_header X-Forwarded-Proto $scheme;
944 }
945
946 # SPA routing
947 location / {
948 try_files $uri $uri/ /index.html;
949 expires 1d;
950 }
951
952 # Security for static assets
953 location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
954 expires 1y;
955 add_header Cache-Control "public, immutable";
956 }
957 }
958}
959```
960 
961## 🚀 Kubernetes Deployment (Optional)
962 
963### Kubernetes Manifests
964```yaml
965# k8s/namespace.yaml
966apiVersion: v1
967kind: Namespace
968metadata:
969 name: pos-system
970 
971---
972# k8s/postgres.yaml
973apiVersion: apps/v1
974kind: StatefulSet
975metadata:
976 name: postgres
977 namespace: pos-system
978spec:
979 serviceName: postgres
980 replicas: 1
981 selector:
982 matchLabels:
983 app: postgres
984 template:
985 metadata:
986 labels:
987 app: postgres
988 spec:
989 containers:
990 - name: postgres
991 image: postgres:15-alpine
992 env:
993 - name: POSTGRES_DB
994 value: pos_system
995 - name: POSTGRES_USER
996 value: postgres
997 - name: POSTGRES_PASSWORD
998 valueFrom:
999 secretKeyRef:
1000 name: postgres-secret
1001 key: password
1002 volumeMounts:
1003 - name: postgres-storage
1004 mountPath: /var/lib/postgresql/data
1005 ports:
1006 - containerPort: 5432
1007 livenessProbe:
1008 exec:
1009 command: ["pg_isready", "-U", "postgres"]
1010 initialDelaySeconds: 30
1011 periodSeconds: 10
1012 readinessProbe:
1013 exec:
1014 command: ["pg_isready", "-U", "postgres"]
1015 initialDelaySeconds: 5
1016 periodSeconds: 5
1017 volumeClaimTemplates:
1018 - metadata:
1019 name: postgres-storage
1020 spec:
1021 accessModes: ["ReadWriteOnce"]
1022 resources:
1023 requests:
1024 storage: 10Gi
1025 
1026---
1027# k8s/backend.yaml
1028apiVersion: apps/v1
1029kind: Deployment
1030metadata:
1031 name: backend
1032 namespace: pos-system
1033spec:
1034 replicas: 2
1035 selector:
1036 matchLabels:
1037 app: backend
1038 template:
1039 metadata:
1040 labels:
1041 app: backend
1042 spec:
1043 containers:
1044 - name: backend
1045 image: your-registry/pos-backend:latest
1046 env:
1047 - name: DB_HOST
1048 value: postgres-service
1049 - name: DB_PASSWORD
1050 valueFrom:
1051 secretKeyRef:
1052 name: postgres-secret
1053 key: password
1054 ports:
1055 - containerPort: 8080
1056 livenessProbe:
1057 httpGet:
1058 path: /health
1059 port: 8080
1060 initialDelaySeconds: 30
1061 periodSeconds: 10
1062 readinessProbe:
1063 httpGet:
1064 path: /health
1065 port: 8080
1066 initialDelaySeconds: 5
1067 periodSeconds: 5
1068 resources:
1069 requests:
1070 memory: "256Mi"
1071 cpu: "250m"
1072 limits:
1073 memory: "512Mi"
1074 cpu: "500m"
1075```
1076 
1077## 📈 Performance & Scaling Patterns
1078 
1079### Horizontal Pod Autoscaling (K8s)
1080```yaml
1081apiVersion: autoscaling/v2
1082kind: HorizontalPodAutoscaler
1083metadata:
1084 name: backend-hpa
1085 namespace: pos-system
1086spec:
1087 scaleTargetRef:
1088 apiVersion: apps/v1
1089 kind: Deployment
1090 name: backend
1091 minReplicas: 2
1092 maxReplicas: 10
1093 metrics:
1094 - type: Resource
1095 resource:
1096 name: cpu
1097 target:
1098 type: Utilization
1099 averageUtilization: 70
1100 - type: Resource
1101 resource:
1102 name: memory
1103 target:
1104 type: Utilization
1105 averageUtilization: 80
1106```
1107 
1108### Docker Swarm Scaling
1109```bash
1110# Scale services in Docker Swarm
1111docker service scale pos-system_backend=3
1112docker service scale pos-system_frontend=2
1113 
1114# Rolling updates
1115docker service update --image pos-backend:v1.2.3 pos-system_backend
1116```
1117 
1118## 🔧 Advanced Deployment Tools
1119 
1120### Makefile Enhancement for Production
1121```makefile
1122# Production deployment commands
1123.PHONY: deploy-prod deploy-staging backup-prod restore-prod
1124 
1125deploy-prod: ## Deploy to production
1126 @echo "🚀 Deploying to production..."
1127 docker stack deploy -c docker-compose.prod.yml pos-system
1128 @echo "✅ Production deployment complete"
1129 
1130deploy-staging: ## Deploy to staging
1131 @echo "🧪 Deploying to staging..."
1132 docker-compose -f docker-compose.staging.yml up -d
1133 @echo "✅ Staging deployment complete"
1134 
1135backup-prod: ## Backup production database
1136 @echo "💾 Creating production backup..."
1137 docker exec $$(docker ps -q -f name=pos-postgres) pg_dump -U postgres pos_system > "backup-prod-$$(date +%Y%m%d-%H%M%S).sql"
1138 @echo "✅ Production backup complete"
1139 
1140restore-prod: ## Restore production from backup
1141 @read -p "Enter backup file path: " backup; \
1142 echo "🔄 Restoring production from $$backup..."; \
1143 docker exec -i $$(docker ps -q -f name=pos-postgres) psql -U postgres pos_system < $$backup
1144 @echo "✅ Production restore complete"
1145 
1146health-check: ## Check production health
1147 @echo "🏥 Checking system health..."
1148 @curl -f http://localhost/health || echo "❌ Frontend health check failed"
1149 @curl -f http://localhost:8080/health || echo "❌ Backend health check failed"
1150 @echo "✅ Health checks complete"
1151```

Commands it names

  • docker-compose -f docker-compose.dev.yml up
  • docker-compose up -d
  • docker exec pos-postgres pg_dump -U postgres pos_system > backup.sql
  • docker exec -i pos-postgres psql -U postgres pos_system < backup.sql
  • make dev
  • make up
  • make down
  • make status
  • make create-admin
  • make backup
  • make restore
  • make db-shell
  • make db-reset
  • docker-compose logs -f backend
  • docker-compose down
  • docker-compose up --build
  • docker build -t pos-backend:latest ./backend
  • docker build -t pos-frontend:latest ./frontend
  • docker tag pos-backend:latest your-registry/pos-backend:v1.0.0
  • docker tag pos-frontend:latest your-registry/pos-frontend:v1.0.0
  • docker push your-registry/pos-backend:v1.0.0
  • docker push your-registry/pos-frontend:v1.0.0
  • docker-compose logs [service-name]
  • docker-compose exec backend sh
  • docker-compose exec postgres psql -U postgres pos_system
  • docker-compose exec backend wget -qO- http://postgres:5432
  • docker inspect pos-backend
  • docker buildx create --name pos-builder --use
  • docker buildx build --platform linux/amd64,linux/arm64 -t pos-backend:latest ./backend --push
  • docker build -t pos-backend:1.2.3 ./backend
  • docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
  • docker stack deploy -c docker-compose.prod.yml pos-system
  • docker secret rm pos_db_password
  • go-version: '1.21'
  • node-version: '18'
  • go test -v -race -coverprofile=coverage.out ./...
  • go tool cover -html=coverage.out -o coverage.html
  • npm ci
  • npm run test:coverage
  • node-exporter:

Sections

  • 🐳 Docker & Production Deployment Guide
  • Container Architecture
  • Service Overview
  • Container Networking
  • Development vs Production
  • Development Configuration
  • Production Configuration
  • Dockerfile Patterns
  • Backend Dockerfile
  • Build stage - full Go toolchain
  • Production stage - minimal runtime
  • Frontend Dockerfile
  • Build stage
  • Production stage - Nginx
  • Environment Configuration
  • Environment Variables
  • Database
  • Backend
  • Frontend
  • Security Considerations
  • Volume Management
  • Persistent Data Storage
  • Development Volume Mounts
  • Nginx Configuration
  • Reverse Proxy Setup
  • API proxy to backend
  • SPA routing for React
  • Performance Optimization
  • Health Checks & Monitoring
  • Container Health Checks
  • Restart Policies
  • Database Initialization
  • Schema & Seed Data
  • Backup Strategies
  • Create database backup
  • Restore database
  • Development Workflow
  • Essential commands
  • Database Operations
  • Interactive database management
  • Legacy Commands (use Makefile instead)
  • Start all services (legacy)
  • View logs (use: make logs)
  • Stop services (use: make down)
  • Rebuild containers (use: make rebuild)
  • Production Deployment
  • Container Registry
  • Build images
  • Tag for registry
  • Push to registry
  • Deployment Checklist
  • Security Best Practices
  • Container Security
  • Network Security
  • Performance Optimization
  • Build Optimization
  • Runtime Optimization
  • Troubleshooting
  • Common Issues
  • Debugging Commands

What it covers

setupbuildtestcode-stylearchitecturetypessecuritydatabaseapiperformancedeploymentagent-behaviour

Stack — with the evidence

typescript

(1.00)

react

(1.00)

tailwind

(1.00)

docker

(1.00)

vite

(0.70)

eslint

(0.70)

node

(0.50)

javascript

(0.50)

Glob targeting

  • Dockerfile
  • Dockerfile.*
  • docker-compose.*
  • *.sh
  • nginx.conf
  • .github/workflows/*
  • k8s/*
  • *.yml
  • *.yaml

Format

Cursor rules

The most expressive format here. Many small .mdc files, each with frontmatter declaring when it should load, so a rule about migrations only enters context when a migration is open. Costs the most to maintain and only one editor reads it.

What the corpus says about it

Repository

Owner
madebyaris
Language
—
License
—
Archived
no

All configs in this repo

Also in madebyaris/poinf-of-sales

Diff this repo’s formats

One repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?

The other instruction files in this repository
RepositoryFormatStackCoversScoreChanged
madebyaris/poinf-of-sales.cursor/rules/admin-interface-patterns.mdc · 118Cursor rulestypescriptreact+5stylearchsecurityapi+262/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/api-patterns.mdc · 118Cursor rulestypescriptreact+5lint-formatstylesecuritydatabase+362/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/authentication-and-security-patterns.mdc · 118Cursor rulestypescriptreact+5setupteststylesecurity+481/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/backend-golang.mdc · 118Cursor rulestypescriptreact+5testlint-formatstylearch+569/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/business-logic-patterns.mdc · 118Cursor rulestypescriptreact+5teststyledatabaseperformance+150/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/database-patterns.mdc · 118Cursor rulestypescriptreact+5stylearchtypessecurity+262/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/development-workflow.mdc · 118Cursor rulestypescriptreact+5setupbuildteststyle+386/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/frontend-react.mdc · 118Cursor rulestypescriptreact+5buildtestlint-formatstyle+469/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/makefile-scripting.mdc · 118Cursor rulestypescriptreact+5setuplint-formatstylearch+281/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/performance-optimization-patterns.mdc · 118Cursor rulestypescriptreact+5buildteststyledatabase+366/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/project-architecture.mdc · 118Cursor rulestypescriptreact+5setupteststylearch+678/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/react-native-mobile-patterns.mdc · 118Cursor rulestypescriptreact+5buildstylearchui+274/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/role-based-access-patterns.mdc · 118Cursor rulestypescriptreact+5styletypessecuritydatabase+258/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/tech-debt-prevention.mdc · 118Cursor rulestypescriptreact+5styletesting-strategyui50/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/testing-patterns.mdc · 118Cursor rulestypescriptreact+6setupteststylearch+474/1003 days ago
madebyaris/poinf-of-sales.cursor/rules/user-journey-optimization.mdc · 118Cursor rulestypescriptreact+5styleperformanceagent-behaviour50/1003 days ago
Diff against .cursor/rules/admin-interface-patterns.mdc Diff against .cursor/rules/api-patterns.mdc Diff against .cursor/rules/authentication-and-security-patterns.mdc Diff against .cursor/rules/backend-golang.mdc Diff against .cursor/rules/business-logic-patterns.mdc Diff against .cursor/rules/database-patterns.mdc Diff against .cursor/rules/development-workflow.mdc Diff against .cursor/rules/frontend-react.mdc Diff against .cursor/rules/makefile-scripting.mdc Diff against .cursor/rules/performance-optimization-patterns.mdc Diff against .cursor/rules/project-architecture.mdc Diff against .cursor/rules/react-native-mobile-patterns.mdc Diff against .cursor/rules/role-based-access-patterns.mdc Diff against .cursor/rules/tech-debt-prevention.mdc Diff against .cursor/rules/testing-patterns.mdc Diff against .cursor/rules/user-journey-optimization.mdc

Similar configs

Same format, overlapping stack, ranked by quality.

Same format, overlapping stack, ranked by quality
RepositoryFormatStackCoversScoreChanged
hiromaily/go-crypto-wallet.cursor/rules/typescript.mdc · 126Cursor rulesgobun+5setupbuildtestlint-format+6100/1003 days ago
TechSquidTV/Hermes.cursor/rules/10-hermes-api.mdc · 45Cursor rulestypescriptpytest+15testlint-formatstylearch+5100/1003 days ago
dodgecfr/combatfilms-webapp.cursor/rules/frontend.mdc · 0Cursor rulestypescriptturborepo+15setuptestlint-formatstyle+799/1003 days ago
deifos/clipmira-subtitles.cursor/rules/frontend.mdc · 1Cursor rulestypescriptnextjs+5setuptestlint-formatstyle+799/1003 days ago
markstev/mark-starter.cursor/rules/frontend.mdc · 0Cursor rulestypescriptturborepo+14setuptestlint-formatstyle+699/1003 days ago
Allymahmoud/case-intake-platform.cursor/rules/frontend.mdc · 0Cursor rulestypescriptturborepo+13setuptestlint-formatstyle+799/1003 days ago
langflow-ai/langflow.cursor/rules/docs_development.mdc · 153kCursor rulespythonnode+16setupbuildtestlint-format+797/1003 days ago
TechSquidTV/Hermes.cursor/rules/20-hermes-api-tests.mdc · 45Cursor rulestypescriptpytest+15teststyletesting-strategysecurity+397/1003 days ago
RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack

RuleStack

Built by

Kynth Studio

Directory

Configs
Stacks
Compare formats
Diff two configs
Best AGENTS.md examples

Formats

AGENTS.md
CLAUDE.md
Cursor rules
Copilot instructions

Reference

Read API
Corpus health
Privacy Policy
Terms

RuleStack