---
title: "GCP Deployment"
description: "Deploy TraceRTM on Google Cloud Platform using Compute Engine, Cloud Run, or GKE"
---

# GCP Deployment

Deploy TraceRTM on Google Cloud Platform (GCP) with comprehensive infrastructure setup including Cloud SQL, Memorystore, and monitoring.

## Overview

This guide covers deploying TraceRTM on GCP using:

- **Compute Engine**: Virtual machines with full control
- **Cloud Run**: Serverless containerized deployment
- **Google Kubernetes Engine (GKE)**: Scalable container orchestration
- **Cloud SQL**: Managed PostgreSQL database
- **Memorystore**: Managed Redis cache
- **Cloud Storage**: Object storage for backups and static files
- **Cloud Load Balancing**: Global load balancing
- **Cloud Monitoring/Logging**: Observability stack

## Prerequisites

### GCP Account and Project

1. **Create a GCP Account**: Sign up at [cloud.google.com](https://cloud.google.com)
2. **Create a Project**:

```bash
# Set your project ID
export PROJECT_ID="tracertm-prod"
export REGION="us-central1"
export ZONE="us-central1-a"

# Create project
gcloud projects create $PROJECT_ID --name="TraceRTM Production"

# Set default project
gcloud config set project $PROJECT_ID
gcloud config set compute/region $REGION
gcloud config set compute/zone $ZONE
```

3. **Enable Billing**:

```bash
# Link billing account (get BILLING_ACCOUNT_ID from console)
gcloud billing projects link $PROJECT_ID \
  --billing-account=BILLING_ACCOUNT_ID
```

### Install gcloud CLI

**macOS**:
```bash
brew install google-cloud-sdk
```

**Linux**:
```bash
curl https://sdk.cloud.google.com | bash
exec -l $SHELL
```

**Windows**: Download from [cloud.google.com/sdk/docs/install](https://cloud.google.com/sdk/docs/install)

### Initialize gcloud

```bash
# Authenticate
gcloud auth login

# Set application default credentials
gcloud auth application-default login
```

### Enable Required APIs

```bash
# Enable all required GCP APIs
gcloud services enable \
  compute.googleapis.com \
  run.googleapis.com \
  container.googleapis.com \
  sqladmin.googleapis.com \
  redis.googleapis.com \
  storage.googleapis.com \
  cloudbuild.googleapis.com \
  cloudresourcemanager.googleapis.com \
  iam.googleapis.com \
  dns.googleapis.com \
  logging.googleapis.com \
  monitoring.googleapis.com \
  secretmanager.googleapis.com
```

## IAM and Service Accounts

### Create Service Accounts

```bash
# Application service account
gcloud iam service-accounts create tracertm-app \
  --display-name="TraceRTM Application Service Account"

# Set environment variables
export APP_SA="tracertm-app@${PROJECT_ID}.iam.gserviceaccount.com"

# Grant necessary roles
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${APP_SA}" \
  --role="roles/cloudsql.client"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${APP_SA}" \
  --role="roles/redis.editor"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${APP_SA}" \
  --role="roles/storage.objectAdmin"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${APP_SA}" \
  --role="roles/logging.logWriter"

gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member="serviceAccount:${APP_SA}" \
  --role="roles/monitoring.metricWriter"
```

### Create Service Account Key (for Compute Engine)

```bash
gcloud iam service-accounts keys create ~/tracertm-key.json \
  --iam-account=$APP_SA

# Securely store the key
chmod 600 ~/tracertm-key.json
```

## Cloud SQL for PostgreSQL

### Create Cloud SQL Instance

```bash
# Create PostgreSQL instance
gcloud sql instances create tracertm-db \
  --database-version=POSTGRES_15 \
  --tier=db-custom-2-8192 \
  --region=$REGION \
  --network=default \
  --enable-bin-log \
  --backup-start-time=03:00 \
  --maintenance-window-day=SUN \
  --maintenance-window-hour=04 \
  --root-password=$(openssl rand -base64 32)

# Create database
gcloud sql databases create tracertm \
  --instance=tracertm-db

# Create database user
export DB_PASSWORD=$(openssl rand -base64 32)
gcloud sql users create tracertm \
  --instance=tracertm-db \
  --password=$DB_PASSWORD

# Store password in Secret Manager
echo -n $DB_PASSWORD | gcloud secrets create db-password --data-file=-
```

### Configure Cloud SQL Proxy (for local development)

```bash
# Download Cloud SQL Proxy
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
chmod +x cloud_sql_proxy

# Get connection name
export CONNECTION_NAME=$(gcloud sql instances describe tracertm-db \
  --format='value(connectionName)')

# Run proxy
./cloud_sql_proxy -instances=$CONNECTION_NAME=tcp:5432 &
```

### High Availability Configuration

```bash
# Create HA instance
gcloud sql instances create tracertm-db-ha \
  --database-version=POSTGRES_15 \
  --tier=db-custom-4-16384 \
  --region=$REGION \
  --availability-type=REGIONAL \
  --backup-start-time=03:00 \
  --enable-point-in-time-recovery
```

## Memorystore for Redis

### Create Redis Instance

```bash
# Create Redis instance
gcloud redis instances create tracertm-cache \
  --size=1 \
  --region=$REGION \
  --redis-version=redis_6_x \
  --tier=basic

# For production, use standard tier with HA
gcloud redis instances create tracertm-cache-prod \
  --size=5 \
  --region=$REGION \
  --redis-version=redis_6_x \
  --tier=standard-ha \
  --replica-count=1

# Get Redis host
export REDIS_HOST=$(gcloud redis instances describe tracertm-cache \
  --region=$REGION --format='value(host)')
export REDIS_PORT=$(gcloud redis instances describe tracertm-cache \
  --region=$REGION --format='value(port)')
```

## Cloud Storage

### Create Storage Buckets

```bash
# Create bucket for application storage
gsutil mb -p $PROJECT_ID -c STANDARD -l $REGION gs://${PROJECT_ID}-storage

# Create bucket for backups
gsutil mb -p $PROJECT_ID -c NEARLINE -l $REGION gs://${PROJECT_ID}-backups

# Enable versioning on storage bucket
gsutil versioning set on gs://${PROJECT_ID}-storage

# Set lifecycle policy for backups
cat > lifecycle.json <<EOF
{
  "lifecycle": {
    "rule": [
      {
        "action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
        "condition": {"age": 90}
      },
      {
        "action": {"type": "Delete"},
        "condition": {"age": 365}
      }
    ]
  }
}
EOF

gsutil lifecycle set lifecycle.json gs://${PROJECT_ID}-backups

# Set IAM permissions
gsutil iam ch serviceAccount:${APP_SA}:objectAdmin \
  gs://${PROJECT_ID}-storage
gsutil iam ch serviceAccount:${APP_SA}:objectCreator \
  gs://${PROJECT_ID}-backups
```

## Deployment Option 1: Compute Engine

### Create VM Instance

```bash
# Create compute instance
gcloud compute instances create tracertm-vm \
  --machine-type=n2-standard-2 \
  --image-family=ubuntu-2204-lts \
  --image-project=ubuntu-os-cloud \
  --boot-disk-size=50GB \
  --boot-disk-type=pd-ssd \
  --service-account=$APP_SA \
  --scopes=cloud-platform \
  --tags=http-server,https-server \
  --metadata=startup-script='#!/bin/bash
apt-get update
apt-get install -y docker.io docker-compose git
systemctl enable docker
systemctl start docker
'
```

### SSH and Deploy

```bash
# SSH into instance
gcloud compute ssh tracertm-vm

# On the VM: Clone repository
git clone https://github.com/yourusername/tracertm.git
cd tracertm

# Create .env file
cat > .env <<EOF
DATABASE_URL=postgresql://tracertm:${DB_PASSWORD}@/tracertm?host=/cloudsql/${CONNECTION_NAME}
REDIS_URL=redis://${REDIS_HOST}:${REDIS_PORT}
STORAGE_BUCKET=${PROJECT_ID}-storage
BACKUP_BUCKET=${PROJECT_ID}-backups
GCP_PROJECT_ID=${PROJECT_ID}
EOF

# Deploy with Docker Compose
docker-compose up -d
```

### Create Instance Template and Managed Instance Group

```bash
# Create instance template
gcloud compute instance-templates create tracertm-template \
  --machine-type=n2-standard-2 \
  --image-family=ubuntu-2204-lts \
  --image-project=ubuntu-os-cloud \
  --boot-disk-size=50GB \
  --service-account=$APP_SA \
  --scopes=cloud-platform \
  --tags=http-server,https-server \
  --metadata-from-file=startup-script=startup.sh

# Create managed instance group
gcloud compute instance-groups managed create tracertm-mig \
  --base-instance-name=tracertm-vm \
  --template=tracertm-template \
  --size=3 \
  --region=$REGION

# Configure autoscaling
gcloud compute instance-groups managed set-autoscaling tracertm-mig \
  --region=$REGION \
  --min-num-replicas=2 \
  --max-num-replicas=10 \
  --target-cpu-utilization=0.7 \
  --cool-down-period=60
```

## Deployment Option 2: Cloud Run

### Build and Push Container

```bash
# Build with Cloud Build
gcloud builds submit --tag gcr.io/$PROJECT_ID/tracertm

# Or build locally and push
docker build -t gcr.io/$PROJECT_ID/tracertm .
docker push gcr.io/$PROJECT_ID/tracertm
```

### Deploy to Cloud Run

```bash
# Deploy Cloud Run service
gcloud run deploy tracertm \
  --image=gcr.io/$PROJECT_ID/tracertm \
  --platform=managed \
  --region=$REGION \
  --service-account=$APP_SA \
  --allow-unauthenticated \
  --min-instances=1 \
  --max-instances=10 \
  --memory=2Gi \
  --cpu=2 \
  --timeout=300 \
  --concurrency=100 \
  --set-env-vars="REDIS_HOST=${REDIS_HOST},REDIS_PORT=${REDIS_PORT}" \
  --set-secrets="DATABASE_URL=db-url:latest" \
  --add-cloudsql-instances=$CONNECTION_NAME \
  --vpc-connector=tracertm-connector

# Get service URL
gcloud run services describe tracertm \
  --region=$REGION \
  --format='value(status.url)'
```

### Create VPC Connector (for Cloud SQL and Redis)

```bash
# Create VPC connector
gcloud compute networks vpc-access connectors create tracertm-connector \
  --region=$REGION \
  --range=10.8.0.0/28 \
  --network=default
```

## Deployment Option 3: Google Kubernetes Engine (GKE)

### Create GKE Cluster

```bash
# Create GKE cluster
gcloud container clusters create tracertm-cluster \
  --region=$REGION \
  --num-nodes=1 \
  --machine-type=n2-standard-2 \
  --enable-autoscaling \
  --min-nodes=1 \
  --max-nodes=5 \
  --enable-autorepair \
  --enable-autoupgrade \
  --enable-ip-alias \
  --network=default \
  --workload-pool=${PROJECT_ID}.svc.id.goog

# Get cluster credentials
gcloud container clusters get-credentials tracertm-cluster --region=$REGION
```

### Deploy to GKE

```bash
# Create namespace
kubectl create namespace tracertm

# Create secrets
kubectl create secret generic db-credentials \
  --from-literal=username=tracertm \
  --from-literal=password=$DB_PASSWORD \
  --from-literal=host=$CONNECTION_NAME \
  --namespace=tracertm

kubectl create secret generic redis-config \
  --from-literal=host=$REDIS_HOST \
  --from-literal=port=$REDIS_PORT \
  --namespace=tracertm

# Deploy application
cat > deployment.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: tracertm
  namespace: tracertm
spec:
  replicas: 3
  selector:
    matchLabels:
      app: tracertm
  template:
    metadata:
      labels:
        app: tracertm
    spec:
      serviceAccountName: tracertm-ksa
      containers:
      - name: tracertm
        image: gcr.io/$PROJECT_ID/tracertm:latest
        ports:
        - containerPort: 8000
        env:
        - name: DATABASE_URL
          valueFrom:
            secretKeyRef:
              name: db-credentials
              key: url
        - name: REDIS_HOST
          valueFrom:
            secretKeyRef:
              name: redis-config
              key: host
        resources:
          requests:
            memory: "1Gi"
            cpu: "500m"
          limits:
            memory: "2Gi"
            cpu: "1000m"
      - name: cloud-sql-proxy
        image: gcr.io/cloudsql-docker/gce-proxy:latest
        command:
        - "/cloud_sql_proxy"
        - "-instances=$CONNECTION_NAME=tcp:5432"
---
apiVersion: v1
kind: Service
metadata:
  name: tracertm-service
  namespace: tracertm
spec:
  type: LoadBalancer
  selector:
    app: tracertm
  ports:
  - port: 80
    targetPort: 8000
EOF

kubectl apply -f deployment.yaml
```

### Configure Workload Identity

```bash
# Create Kubernetes service account
kubectl create serviceaccount tracertm-ksa --namespace=tracertm

# Bind KSA to GSA
gcloud iam service-accounts add-iam-policy-binding $APP_SA \
  --role roles/iam.workloadIdentityUser \
  --member "serviceAccount:${PROJECT_ID}.svc.id.goog[tracertm/tracertm-ksa]"

# Annotate KSA
kubectl annotate serviceaccount tracertm-ksa \
  --namespace=tracertm \
  iam.gke.io/gcp-service-account=$APP_SA
```

## Cloud Load Balancing

### Create Load Balancer for Compute Engine

```bash
# Create health check
gcloud compute health-checks create http tracertm-health-check \
  --port=8000 \
  --request-path=/health

# Create backend service
gcloud compute backend-services create tracertm-backend \
  --protocol=HTTP \
  --health-checks=tracertm-health-check \
  --global

# Add instance group to backend
gcloud compute backend-services add-backend tracertm-backend \
  --instance-group=tracertm-mig \
  --instance-group-region=$REGION \
  --global

# Create URL map
gcloud compute url-maps create tracertm-lb \
  --default-service=tracertm-backend

# Create HTTP(S) target proxy
gcloud compute target-http-proxies create tracertm-http-proxy \
  --url-map=tracertm-lb

# Create SSL certificate
gcloud compute ssl-certificates create tracertm-cert \
  --domains=tracertm.yourdomain.com

gcloud compute target-https-proxies create tracertm-https-proxy \
  --url-map=tracertm-lb \
  --ssl-certificates=tracertm-cert

# Create forwarding rules
gcloud compute forwarding-rules create tracertm-http-rule \
  --global \
  --target-http-proxy=tracertm-http-proxy \
  --ports=80

gcloud compute forwarding-rules create tracertm-https-rule \
  --global \
  --target-https-proxy=tracertm-https-proxy \
  --ports=443
```

## Cloud DNS Configuration

### Create DNS Zone and Records

```bash
# Create managed zone
gcloud dns managed-zones create tracertm-zone \
  --dns-name=tracertm.yourdomain.com. \
  --description="TraceRTM DNS Zone"

# Get load balancer IP
export LB_IP=$(gcloud compute forwarding-rules describe tracertm-https-rule \
  --global --format='value(IPAddress)')

# Create A record
gcloud dns record-sets create tracertm.yourdomain.com. \
  --zone=tracertm-zone \
  --type=A \
  --ttl=300 \
  --rrdatas=$LB_IP

# Create CNAME for www
gcloud dns record-sets create www.tracertm.yourdomain.com. \
  --zone=tracertm-zone \
  --type=CNAME \
  --ttl=300 \
  --rrdatas=tracertm.yourdomain.com.
```

## Cloud Monitoring and Logging

### Enable Cloud Monitoring

```bash
# Install monitoring agent on Compute Engine
curl -sSO https://dl.google.com/cloudagents/add-google-cloud-ops-agent-repo.sh
sudo bash add-google-cloud-ops-agent-repo.sh --also-install

# Create uptime check
gcloud monitoring uptime-check-configs create tracertm-uptime \
  --display-name="TraceRTM Uptime Check" \
  --resource-type=uptime-url \
  --host=tracertm.yourdomain.com \
  --path=/health \
  --check-interval=60s

# Create alert policy
cat > alert-policy.json <<EOF
{
  "displayName": "TraceRTM High Error Rate",
  "conditions": [{
    "displayName": "Error rate > 5%",
    "conditionThreshold": {
      "filter": "resource.type=\"gce_instance\" AND metric.type=\"compute.googleapis.com/instance/cpu/utilization\"",
      "comparison": "COMPARISON_GT",
      "thresholdValue": 0.8,
      "duration": "300s"
    }
  }],
  "notificationChannels": [],
  "alertStrategy": {
    "autoClose": "1800s"
  }
}
EOF

gcloud alpha monitoring policies create --policy-from-file=alert-policy.json
```

### Configure Logging

```bash
# Create log sink for long-term storage
gcloud logging sinks create tracertm-logs-archive \
  storage.googleapis.com/${PROJECT_ID}-backups \
  --log-filter='resource.type="gce_instance" OR resource.type="cloud_run_revision" OR resource.type="k8s_container"'

# View logs
gcloud logging read "resource.type=gce_instance" --limit=50 --format=json

# Create log-based metric
gcloud logging metrics create error_count \
  --description="Count of error-level log entries" \
  --log-filter='severity>=ERROR'
```

## Cost Optimization

### Resource Management

```bash
# Set budget alerts
gcloud billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="TraceRTM Monthly Budget" \
  --budget-amount=500 \
  --threshold-rule=percent=50 \
  --threshold-rule=percent=90 \
  --threshold-rule=percent=100

# Use committed use discounts for predictable workloads
gcloud compute commitments create tracertm-commit \
  --region=$REGION \
  --resources=vcpu=8,memory=32 \
  --plan=twelve-month

# Schedule instance shutdown for development
gcloud compute instances add-metadata tracertm-dev \
  --metadata=shutdown-script='#!/bin/bash
docker-compose down
'
```

### Cost-Saving Tips

1. **Use Preemptible VMs for non-production**: 80% cost savings
2. **Enable autoscaling**: Scale to zero during off-hours
3. **Use Cloud Storage lifecycle policies**: Move old data to Coldline/Archive
4. **Choose appropriate machine types**: Use custom machine types
5. **Enable sustained use discounts**: Automatic for long-running instances
6. **Use Cloud CDN**: Reduce egress costs for static content

## Security Best Practices

### Network Security

```bash
# Create firewall rules
gcloud compute firewall-rules create allow-tracertm-http \
  --network=default \
  --allow=tcp:80,tcp:443 \
  --source-ranges=0.0.0.0/0 \
  --target-tags=http-server

gcloud compute firewall-rules create allow-tracertm-internal \
  --network=default \
  --allow=tcp:5432,tcp:6379 \
  --source-tags=tracertm-app

# Deny all other traffic
gcloud compute firewall-rules create deny-all \
  --network=default \
  --action=deny \
  --rules=all \
  --priority=65535
```

### Secret Management

```bash
# Create secrets in Secret Manager
echo -n "your-secret-key" | gcloud secrets create app-secret-key --data-file=-

# Grant access to service account
gcloud secrets add-iam-policy-binding app-secret-key \
  --member="serviceAccount:${APP_SA}" \
  --role="roles/secretmanager.secretAccessor"

# Access in application
gcloud secrets versions access latest --secret="app-secret-key"
```

### Enable Security Features

```bash
# Enable binary authorization for GKE
gcloud container clusters update tracertm-cluster \
  --enable-binauthz \
  --region=$REGION

# Enable VPC Service Controls
gcloud access-context-manager perimeters create tracertm-perimeter \
  --title="TraceRTM Security Perimeter" \
  --resources=projects/$PROJECT_ID \
  --restricted-services=storage.googleapis.com,sqladmin.googleapis.com

# Enable Cloud Armor for DDoS protection
gcloud compute security-policies create tracertm-security-policy \
  --description="TraceRTM security policy"

gcloud compute security-policies rules create 1000 \
  --security-policy=tracertm-security-policy \
  --expression="origin.region_code == 'CN'" \
  --action=deny-403
```

## Backup and Disaster Recovery

### Automated Backups

```bash
# Cloud SQL backups (automatic)
gcloud sql instances patch tracertm-db \
  --backup-start-time=03:00 \
  --enable-bin-log

# Application data backup script
cat > backup.sh <<'EOF'
#!/bin/bash
DATE=$(date +%Y%m%d-%H%M%S)
BACKUP_FILE="tracertm-backup-${DATE}.tar.gz"

# Backup application data
tar -czf $BACKUP_FILE /var/lib/tracertm/data

# Upload to Cloud Storage
gsutil cp $BACKUP_FILE gs://${PROJECT_ID}-backups/

# Cleanup local backup
rm $BACKUP_FILE
EOF

# Schedule with cron
0 3 * * * /usr/local/bin/backup.sh
```

### Disaster Recovery

```bash
# Restore Cloud SQL from backup
gcloud sql backups list --instance=tracertm-db
gcloud sql backups restore BACKUP_ID \
  --backup-instance=tracertm-db \
  --backup-id=BACKUP_ID

# Restore from Cloud Storage
gsutil cp gs://${PROJECT_ID}-backups/tracertm-backup-TIMESTAMP.tar.gz .
tar -xzf tracertm-backup-TIMESTAMP.tar.gz -C /var/lib/tracertm/data
```

## Troubleshooting

### Common Issues

**Cloud SQL Connection Timeout**:
```bash
# Check Cloud SQL instance status
gcloud sql instances describe tracertm-db

# Test connection with Cloud SQL Proxy
./cloud_sql_proxy -instances=$CONNECTION_NAME=tcp:5432
psql -h localhost -U tracertm -d tracertm
```

**Cloud Run Cold Starts**:
```bash
# Set minimum instances
gcloud run services update tracertm \
  --min-instances=1 \
  --region=$REGION
```

**GKE Pod Not Starting**:
```bash
# Check pod status
kubectl get pods -n tracertm
kubectl describe pod POD_NAME -n tracertm
kubectl logs POD_NAME -n tracertm

# Check service account permissions
gcloud iam service-accounts get-iam-policy $APP_SA
```

## Next Steps

- [Configure SSL/TLS](/docs/getting-started/installation/cloud/ssl)
- [Set up CI/CD with Cloud Build](/docs/development/ci-cd)
- [Monitor Performance](/docs/operations/monitoring)
- [Scale Your Deployment](/docs/operations/scaling)

## Additional Resources

- [GCP Architecture Center](https://cloud.google.com/architecture)
- [GCP Pricing Calculator](https://cloud.google.com/products/calculator)
- [Cloud SQL Best Practices](https://cloud.google.com/sql/docs/postgres/best-practices)
- [GKE Best Practices](https://cloud.google.com/kubernetes-engine/docs/best-practices)
