# Joshua Ansah — Portfolio Reference

> Software engineer Joshua Ansah builds web and mobile applications, APIs, and fintech and SaaS products. Explore his projects, experience, skills, and articles.

This Markdown document summarizes the public portfolio and contains the full text of published project and blog pages. The canonical website is https://joshua-ansah.vercel.app.

## Profile

Joshua Ansah is a software engineer. The portfolio presents work across web and mobile software, fintech, SaaS, APIs, and production systems.

## Contact and profiles

- Email: mr.joshua.ansah@gmail.com
- GitHub: https://github.com/teebhagg
- LinkedIn: https://www.linkedin.com/in/joshua-ansah-b0a15a230/
- Resume: https://joshua-ansah.vercel.app/resume.pdf

## Skills

### Programming Languages

Proficient in modern programming languages that power web and mobile applications:

 - JavaScript
 - TypeScript
 - Dart

### Frontend Development

Expertise in creating responsive, interactive, and user-friendly interfaces using modern frameworks and libraries:

 - React.js
 - Next.js
 - Tailwind CSS
 - Material-UI
 - Bootstrap

### Backend Development

Experience building robust server-side applications and APIs to support web and mobile applications:

 - Node.js
 - Express.js
 - Nest.js

### Mobile Development

Skilled in developing cross-platform mobile applications with a focus on performance and user experience:

 - Flutter
 - React Native
 - Expo

### Database Management

Knowledge of various database systems for efficient data storage, retrieval, and management:

 - MongoDB
 - PostgreSQL
 - Firebase

### Tools & Platforms

Proficient with industry-standard tools and platforms that enhance development workflow and collaboration:

 - Git
 - GitHub
 - Notion
 - Figma
 - Docker
 - CI/CD
 - Redux

### AI & Developer Tools

AI and developer tools used for feature prototyping and refactoring:

 - Cursor
 - Codex
 - LLM-assisted development

### Methodologies

Experience with software development methodologies and practices that ensure efficient project delivery:

 - Agile
 - Project Management
 - SDLC (Software Development Life Cycle)

### Soft Skills

Essential interpersonal abilities that complement technical skills and facilitate effective teamwork:

 - Communication
 - Collaboration
 - Teamwork
 - Problem-Solving

## Experience

### Chale Lets Links Up — Freelance Software Engineer (Contract)

Aug 2026 - Present

- Built and launched responsive production websites for Chale Link Up and Bomuara using React.
- Developed Bomuara's cross-platform iOS and Android application using React Native and Expo.
- Implemented authentication, messaging, payment, notification, and analytics flows in the mobile apps.

### Fluid Finance Technologies — Full-Stack Engineer

Oct 2024 - Jul 2026

- Engineered and launched 5+ critical features for customer-facing fintech web apps using Flutter, React, TypeScript, Node.js, and PostgreSQL.
- Reduced production incidents by 30% by introducing a data sanitation strategy and resolving 50+ critical bugs.
- Designed and implemented an internal admin dashboard automating major manual workflows, saving the team 10+ hours per month.
- Improved the GitHub Actions CI/CD pipeline, reducing failed deployments and speeding up releases.
- Collaborated with product managers and designers in Agile sprints to translate requirements into features, participate in code reviews, and deliver work through Git-based workflows.
- Utilized AI-assisted development tools as part of the daily workflow, while enforcing code review and team standards.

### Verified Global E-Transport — Lead Software Engineer (Contract)

Mar 2025 - Sep 2025

- Led a three-member engineering team delivering logistics and transport management solutions, using Flutter, React, Node.js/Express.js, TypeScript, and PostgreSQL.
- Designed backend services for bookings, routing, and user management using Node.js, Express, TypeScript, and PostgreSQL.
- Introduced Agile practices and managed sprint planning in Notion, improving the team's sprint completion rate by 25% and increasing delivery predictability for stakeholders.
- Established new coding standards and a mandatory code review process that decreased the bug rate in new features by 40% in the first three months.

### Seymo — Software Developer

Mar 2023 - Sep 2024

- Built attendance, fee tracking, and push notification modules for Seymo School, a product used by 1,000+ users.
- Owned the development of key mobile features in Flutter, delivering a consistent and performant experience for users on both Android and iOS.
- Partnered with the design team to build a shared component library that unified our UI and sped up our development cycle, allowing us to ship new features approximately 20% faster.

### Freelance (concurrent) — Full-Stack Developer

Feb 2023 - Sep 2024

- Partnered directly with clients to build and launch custom web applications, handling the full lifecycle from initial design to deployment and maintenance.
- Launched the Green Ghana mobile app on both iOS and Android, collaborating with another developer to deliver a user-friendly Flutter application for a key government initiative.
- Developed the Moyosore blogging and audio platform, implementing the Sanity CMS backend that cut the client's content publishing time by half.

### Spayces — Front End Developer

Sep 2022 - Nov 2022

- Brought a key product feature to life by building its entire front-end, delivering a responsive and pixel-perfect UI in React.js for a critical release.
- Partnered with backend engineers to seamlessly integrate REST APIs, ensuring the new feature had smooth data flow and robust error handling for a stable user experience.

### Ghana Tech Lab — Flutter Developer

Sep 2021 - Aug 2022

- Played a key role in developing The Mechanic, a service marketplace app, where I built the end-to-end user booking and service feedback features in Flutter.
- Worked closely with designers to transform Figma mockups into interactive Flutter prototypes, allowing our team to rapidly validate new concepts with stakeholders.
- Gained strong foundational web skills by helping build and ship several full-stack projects using HTML, CSS, JavaScript, and collaborative Git workflows.

## Project records

## DayKindle

A personal planner for goals, routines, and daily actions, designed to make room for changing plans.

Category: Mobile App
Technologies: Expo, React Native, TypeScript
- Portfolio page: https://joshua-ansah.vercel.app/projects/daykindle
- Project website: https://daykindle.vercel.app

## A planner that makes room for real life

DayKindle brings goals, routines, daily actions, progress, history, and weekly reflection into one personal planner. It is designed to help people make a plan, follow through where they can, and return to it after a missed or changed day.

---

## CediWise

Smart budgeting tracking and financial literacy mobile app for Ghanaian users. Features income/ expense tracking, savings goals, and financial tips. Cross-platform (Android & iOS).

Technologies: React Native, Expo, TypeScript, Supabase
- Portfolio page: https://joshua-ansah.vercel.app/projects/cedi_wise
- Project website: https://cediwise.app

## 📱 CediWise - Smart Budgeting & Financial Literacy

CediWise is a comprehensive mobile application thoughtfully designed to help Ghanaian users take control of their personal finances. By combining intuitive budgeting tracking with actionable financial literacy, it empowers users to achieve their financial goals.

### 🌟 Key Features

- **📊 Expense & Income Tracking**: Log daily transactions instantly to keep a clear, real-time overview of your cash flow.
- **🎯 Savings Goals**: Define clear benchmarks and visually track your progress toward important financial milestones.
- **💡 Financial Tips**: Access tailored advice and bite-sized insights to improve your overall financial health.
- **📱 Cross-Platform**: Delivers a seamless native experience on both Android and iOS devices.
- **🔐 Secure Data Synchronization**: Built on top of a robust backend architecture prioritizing user data security.

### 🛠️ Technical Architecture

- **React Native & Expo**: Leveraged for rapid, cross-platform mobile development ensuring a smooth, native-like user experience.
- **TypeScript**: Incorporates static typing for a highly maintainable, bug-resistant code foundation.
- **Supabase**: Powers the application backend, providing secure authentication and efficient real-time data synchronization.

---

## GhanaAPI

The definitive REST API for Ghanaian services - Addresses, Exchange Rates, Locations, Transport & Logistics, and more.

Technologies: TypeScript, Node.js, Nest.js, Swagger, REST API
- Portfolio page: https://joshua-ansah.vercel.app/projects/ghana_api
- Project website: https://ghana-api.dev/
- Source code: https://github.com/teebhagg/GhanaAPI
- Documentation: https://docs.ghana-api.dev/
- API reference: https://api.ghana-api.dev/docs

## 🇬🇭 GhanaAPI - The Definitive REST API for Ghanaian Services

GhanaAPI provides developers with unified, reliable access to essential Ghanaian services through a modern REST API. Instead of integrating with multiple fragmented services, developers can access everything through one comprehensive, well-documented API.

### 🔥 Key Features

- **📍 Address & Location Services** - Ghana Post Digital Address validation, geocoding, and location lookup
- **💱 Live Exchange Rates** - Real-time GHS exchange rates with historical data and trends
- **🏛️ Government Data** - Regional information, districts, and official datasets
- **🚗 Transport & Logistics** - Route planning, transport stops, fuel prices, and travel cost estimation
- **⚡ High Performance** - Sub-200ms response times with intelligent caching
- **📊 Developer Friendly** - Interactive Swagger documentation

### 🚀 Project Sections

#### 📚 Documentation

The comprehensive documentation at [docs.ghana-api.dev](https://docs.ghana-api.dev/) provides:

- Getting started guides
- API reference documentation
- Code examples in multiple languages
- Best practices and integration patterns

#### 🔍 API Explorer

Interactive API exploration at [api.ghana-api.dev/docs](https://api.ghana-api.dev/docs) featuring:

- Live API testing interface
- Request/response examples
- Authentication testing
- Real-time data validation

#### 🛠️ Swagger Documentation

Complete OpenAPI specification with:

- Detailed endpoint descriptions
- Request/response schemas
- Authentication requirements
- Error handling documentation

#### 💻 GitHub Repository

Open-source development at [github.com/teebhagg/GhanaAPI](https://github.com/teebhagg/GhanaAPI):

- Full source code access
- Contribution guidelines
- Issue tracking
- Release management

### 🎯 API Endpoints

#### Address & Location Services

- **Validate Digital Address**: `GET /v1/addresses/validate/{digitalCode}`
- **Reverse Geocoding**: `GET /v1/addresses/lookup?lat={latitude}&lng={longitude}`
- **Address Search**: `GET /v1/addresses/search?q={query}&limit={limit}`

#### Exchange Rate Services

- **Current Exchange Rates**: `GET /v1/exchange-rates/current?currencies={currencies}`
- **Historical Exchange Rates**: `GET /v1/exchange-rates/historical?currency={currency}&from={date}&to={date}`

#### Transport & Logistics

- **Calculate Route**: `GET /v1/transport/route-calculation?start_lat={lat}&start_lng={lng}&end_lat={lat}&end_lng={lng}`
- **Get Transport Stops**: `GET /v1/transport/stops?city={city}&type={type}`
- **Get Current Fuel Prices**: `GET /v1/transport/fuel-prices`

### 💡 Quick Example

```javascript
// Get current USD to GHS exchange rate
const response = await fetch(
  'https://api.ghana-api.dev/v1/exchange-rates/current?currencies=USD'
);
const data = await response.json();
console.log(`1 USD = ${data.rates.USD.rate} GHS`);

// Validate Ghana Post Digital Address
const address = await fetch(
  'https://api.ghana-api.dev/v1/addresses/validate/GA-123-4567'
);
const validation = await address.json();
console.log(`Address is ${validation.isValid ? 'valid' : 'invalid'}`);
```

### 🏗️ Technical Architecture

- **Backend**: Node.js with Express.js framework
- **Database**: PostgreSQL for data persistence
- **Documentation**: Swagger/OpenAPI 3.0 specification
- **Deployment**: Docker containerization
- **Performance**: Sub-200ms response times with intelligent caching
- **Monitoring**: Comprehensive logging and error tracking

### 🌟 Impact & Recognition

- **4+ GitHub Stars** and growing community
- **MIT Licensed** open-source project
- **Active Development** with regular updates
- **Developer Community** focused on Ghanaian tech ecosystem

### 🔮 Future Roadmap

- Enhanced mobile SDK development
- Additional government data integration
- Real-time notifications system
- Advanced analytics dashboard
- Multi-language support for local languages

Built with ❤️ for the Ghanaian developer community and made in Ghana 🇬🇭.

---

## Personal Portfolio Website

A personal portfolio to showcase my coding projects, resume, and skills in a beautifully designed format.

Technologies: Next.js, TailwindCSS, TypeScript
- Portfolio page: https://joshua-ansah.vercel.app/projects/portfolio
- Project website: https://joshua-ansah.vercel.app/
- Source code: https://github.com/teebhagg

This is my personal portfolio website where I showcase my coding projects, resume, and skills in a beautifully designed format. I created this website to have an online presence and to share my work with potential employers and clients. The project helped me improve my front-end development skills and learn more about modern web development practices.

---

## Seymo School

A school management mobile app.

Technologies: Flutter, BloC
- Portfolio page: https://joshua-ansah.vercel.app/projects/seymo_school
- Project website: https://play.google.com/store/apps/details?id=com.seymo_schools&hl=en_US/
- Source code: https://github.com/teebhagg/

Managing a school can be tough: a lot of hassle and concerns every day. We’ve got you covered. Seymo School is the user-friendly platform that makes school management seamless and easy. With Seymo, all the time-consuming and tedious processes become smooth and stress-free.

---

## Moyosore Blog Web App

A web app that helps users to read blog posts and listen to its audio recordings.

Technologies: TypeScript, Next.js, TailwindCSS, Sanity.io, Express.js, MongoDB
- Portfolio page: https://joshua-ansah.vercel.app/projects/moyosore
- Project website: https://moyo-sore.com/
- Source code: https://github.com/teebhagg/Moyosore-Web/

This is an e-commerce platform dedicated to eco-friendly products where users can buy, sell, and learn about sustainable living. The goal of this project was to promote sustainable living by providing a marketplace for eco-friendly products. Working on this project helped me understand the intricacies of e-commerce development and the importance of sustainability in business.

---

## Shine Energy

An oil and gas solutions company that has a wide range of petroleum product and service.

Technologies: TypeScript, Next.js, TailwindCSS
- Portfolio page: https://joshua-ansah.vercel.app/projects/shine_energy
- Project website: https://www.shineenergyghana.com/
- Source code: https://github.com/teebhagg

Shine Energy is an oil and gas solutions company that has a wide range of petroleum product and service offerings, tailored uniquely to bring our clients’ visions to life in an efficient and sustainable manner..

---

## Green Ghana

A mobile app for requesting tree seedlings, following planting guidance, and tracking planted trees for Ghana’s Green Ghana initiative.

Technologies: Flutter, Firebase
- Portfolio page: https://joshua-ansah.vercel.app/projects/green_ghana
- Project website: https://play.google.com/store/apps/details?id=org.fcghana.green_ghana&hl=en/
- Source code: https://github.com/teebhagg

Green Ghana is a Forestry Commission of Ghana app for requesting tree seedlings, using planting guides, sharing planting progress, and recording where seedlings have been planted.

---

## Atutor Global

An online learning platform connecting learners with African educators for one-to-one lessons and structured learning pathways.

Category: Web Development
- Portfolio page: https://joshua-ansah.vercel.app/projects/atutorglobal
- Project website: https://atutorglobal.com

## Personalised online learning

Atutor Global connects children, teens, and adults with African educators for one-to-one online learning. Learners can explore pathways for school support, exam preparation, English fluency, and professional English, with structured lessons and progress reporting.


## Blog articles

## Building GhanaAPI: A Comprehensive REST API for Ghanaian Services

Discover how I built GhanaAPI - a unified platform providing developers with reliable access to essential Ghanaian services including digital addresses, exchange rates, transport data, and more.

- Canonical page: https://joshua-ansah.vercel.app/blog/building-ghanaapi-comprehensive-rest-api
- Author: Joshua Ansah
- Published: September 19, 2025
- Category: API Development
- Topics: API, Node.js, TypeScript, Ghana, REST, Digital Services

As a developer passionate about solving real-world problems, I identified a significant gap in the Ghanaian tech ecosystem: the lack of unified, reliable APIs for essential local services. This led me to create **GhanaAPI** - a comprehensive REST API that provides developers with streamlined access to crucial Ghanaian data and services.

## 🎯 The Problem

Before GhanaAPI, developers building applications for the Ghanaian market faced several challenges:

- **Fragmented Services**: Different providers for addresses, exchange rates, and location data
- **Inconsistent APIs**: Varying data formats and response structures
- **Limited Documentation**: Poor or non-existent API documentation
- **Reliability Issues**: Frequent downtime and inconsistent service quality

## 🚀 The Solution: GhanaAPI

GhanaAPI addresses these challenges by providing a single, unified platform with:

### 🏠 **Digital Address Services**

- Ghana Post Digital Address validation and lookup
- Precise geocoding and reverse geocoding
- Address search and standardization
- Sub-200ms response times

### 💱 **Real-time Exchange Rates**

- Live GHS exchange rates from Bank of Ghana
- Historical data and trend analysis
- Multi-currency support (USD, EUR, GBP, NGN)
- Automatic rate updates every hour

### 🌍 **Location & Administrative Data**

- Complete regional and district information
- All 16 Ghana regions with detailed metadata
- Administrative boundaries and geographic data

### 🚗 **Transport & Logistics**

- Route calculation and turn-by-turn directions
- Transport stops and station information
- Real-time fuel prices from National Petroleum Authority
- Travel cost estimation

## 🛠 Technical Architecture

The API is built with modern technologies to ensure scalability and reliability:

- **Backend**: Node.js with TypeScript for type safety
- **Framework**: Express.js with comprehensive middleware
- **Documentation**: OpenAPI 3.0 with interactive Swagger UI
- **Caching**: Intelligent caching for optimal performance
- **Validation**: Comprehensive input validation and error handling

### Key Features:

```javascript
// Example: Get current exchange rates
const rates = await fetch(
  'https://api.ghana-api.dev/v1/exchange-rates/current?currencies=USD,EUR'
);

// Example: Validate digital address
const validation = await fetch(
  'https://api.ghana-api.dev/v1/addresses/validate/GA-123-4567'
);

// Example: Calculate route
const route = await fetch(
  'https://api.ghana-api.dev/v1/transport/route-calculation?start_lat=5.6037&start_lng=-0.187&end_lat=6.6885&end_lng=-1.6244'
);
```

## 📊 Impact & Usage

Since launch, GhanaAPI has:

- **12+ API Endpoints** covering essential Ghanaian services
- **Sub-200ms Response Times** for optimal performance
- **99.9% Uptime** with robust infrastructure
- **Interactive Documentation** at [docs.ghana-api.dev](https://docs.ghana-api.dev)
- **Developer-Friendly** with comprehensive examples and SDKs

## 🌟 What Makes It Special

### Developer Experience First

- **Interactive API Explorer**: Test endpoints directly in the browser
- **Comprehensive Documentation**: Clear examples and use cases
- **Consistent Response Format**: Standardized across all endpoints
- **Error Handling**: Detailed error messages with solution hints

### Built for Ghana

- **Local Data Sources**: Direct integration with official Ghanaian services
- **Cultural Understanding**: API designed with local context in mind
- **Community Driven**: Open for contributions from Ghanaian developers

## 🔮 Future Plans

The roadmap includes:

- **Mobile SDKs** for iOS and Android
- **GraphQL Support** for flexible data querying
- **Webhook Integration** for real-time notifications
- **Extended Transport Data** including timetables and live tracking
- **Weather API** integration
- **Business Registry** lookup services

## 🤝 Open Source & Community

GhanaAPI is open source and welcomes contributions from the developer community. Whether it's bug fixes, new features, or documentation improvements, every contribution helps make the platform better for everyone.

**Key Links:**

- 🌐 [API Website](https://ghana-api.dev)
- 📚 [Documentation](https://docs.ghana-api.dev)
- 🛠 [API Playground](https://api.ghana-api.dev/docs)
- 💻 [GitHub Repository](https://github.com/teebhagg/GhanaAPI)

## 💭 Lessons Learned

Building GhanaAPI taught me valuable lessons about:

- **API Design**: The importance of consistent, intuitive endpoint structure
- **Data Quality**: Ensuring accuracy and reliability of local data sources
- **Performance**: Implementing efficient caching strategies for optimal speed
- **Documentation**: How comprehensive docs can make or break developer adoption
- **Community**: The power of open source collaboration in solving local problems

## 🎉 Conclusion

GhanaAPI represents more than just an API - it's a contribution to Ghana's digital infrastructure. By providing reliable, well-documented access to essential services, it empowers developers to build better applications that serve the Ghanaian community.

The project continues to evolve with feedback from the developer community, and I'm excited about its potential to accelerate digital innovation in Ghana.

---

_Built with ❤️ for the Ghanaian developer community. 🇬🇭_

**Try GhanaAPI today:** [https://ghana-api.dev](https://ghana-api.dev)

---

## Deploying React Apps from Private Repositories to Cloudflare Pages

Learn how to seamlessly deploy React applications from private GitHub repositories or organizations to Cloudflare Pages with automatic deployments and custom domains.

- Canonical page: https://joshua-ansah.vercel.app/blog/deploying-react-private-repo-cloudflare
- Author: Joshua Ansah
- Published: September 19, 2025
- Category: DevOps
- Topics: React, Cloudflare, Deployment, CI/CD, Private Repository, GitHub

Deploying React applications has never been easier with modern platforms like Cloudflare Pages. However, when your code lives in a private repository or organization, the process requires some additional configuration. In this comprehensive guide, I'll walk you through the entire process of deploying your React app from a private GitHub repository to Cloudflare Pages.

## 🎯 Why Choose Cloudflare Pages?

Before diving into the deployment process, let's understand why Cloudflare Pages is an excellent choice for React applications:

- **Global CDN**: Your app is served from 275+ locations worldwide
- **Zero Configuration**: Automatic builds and deployments
- **Custom Domains**: Easy SSL and domain management
- **Unlimited Bandwidth**: No hidden costs or limits
- **Edge Functions**: Serverless functions at the edge
- **Free Tier**: Generous free plan for personal projects

## 🔐 Prerequisites

Before we start, ensure you have:

- A React application in a private GitHub repository
- A Cloudflare account (free tier works perfectly)
- Admin access to your GitHub organization (if applicable)
- Basic knowledge of Git and React build processes

## 🚀 Step-by-Step Deployment Guide

### Step 1: Prepare Your React Application

First, ensure your React app is production-ready:

```json
// package.json
{
  "name": "my-react-app",
  "version": "0.1.0",
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}
```

Verify your build works locally:

```bash
npm run build
# or
yarn build
```

### Step 2: GitHub Integration Setup

Navigate to [Cloudflare Pages](https://pages.cloudflare.com/) and follow these steps:

1. **Sign in** to your Cloudflare account
2. Go to **Pages** in the dashboard
3. Click **"Connect to Git"**
4. Choose **GitHub** as your Git provider

### Step 3: Authorize Cloudflare for Private Repositories

This is the crucial step for private repositories:

```bash
# When prompted, you'll need to:
# 1. Authorize Cloudflare to access your GitHub account
# 2. Grant permissions to access private repositories
# 3. For organization repos, ensure you have admin access
```

**Important Notes:**

- If you're part of a GitHub organization, the organization admin must approve the Cloudflare app
- You may need to request access from your organization's admin
- Ensure the Cloudflare GitHub app has access to your specific private repository

### Step 4: Repository Selection and Configuration

Once authorized:

```yaml
# Repository Selection
Repository: your-org/private-react-app
Branch: main # or your preferred deployment branch

# Build Configuration
Framework preset: Create React App
Build command: npm run build
Build output directory: build
Root directory: / # unless your React app is in a subdirectory
```

### Step 5: Environment Variables (If Needed)

For React apps with environment variables:

```javascript
// In your Cloudflare Pages settings
REACT_APP_API_URL=https://api.yourdomain.com
REACT_APP_ENV=production
REACT_APP_VERSION=1.0.0
```

**Security Tip**: Never expose sensitive keys in React environment variables as they're bundled with your client-side code.

### Step 6: Custom Build Configuration

For more complex setups, create a custom build configuration:

```javascript
// In your React app root, create a _headers file
/*
  X-Frame-Options: DENY
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block
  Referrer-Policy: strict-origin-when-cross-origin

/static/*
  Cache-Control: public, max-age=31536000, immutable
```

Or use a `_redirects` file for SPA routing:

```
/*    /index.html   200
```

## ⚙️ Advanced Configuration

### Custom Domains

After successful deployment:

1. Go to your Cloudflare Pages project
2. Navigate to **Custom Domains**
3. Add your domain (ensure it's managed by Cloudflare)
4. SSL certificates are automatically provisioned

### Branch Deployments

Configure different branches for different environments:

```yaml
# Production
Branch: main
Domain: yourapp.com

# Staging
Branch: develop
Domain: staging.yourapp.com

# Feature branches
Branch: feature/*
Domain: [branch-name].yourapp.pages.dev
```

### Build Optimization

Optimize your React build for Cloudflare:

```javascript
// In your package.json, add build optimizations
{
  "scripts": {
    "build": "GENERATE_SOURCEMAP=false react-scripts build",
    "build:analyze": "npm run build && npx bundle-analyzer build/static/js/*.js"
  }
}
```

## 🔧 Troubleshooting Common Issues

### Issue 1: Private Repository Not Visible

**Solution:**

```bash
# Ensure proper GitHub app permissions
1. Go to GitHub Settings > Applications > Authorized OAuth Apps
2. Find Cloudflare Pages
3. Grant access to your organization
4. Refresh the repository list in Cloudflare
```

### Issue 2: Build Failures

**Common causes and solutions:**

```bash
# Node version mismatch
# Add .nvmrc file to your repo
echo "18" > .nvmrc

# Missing dependencies
# Ensure package-lock.json is committed
git add package-lock.json
git commit -m "Add package-lock.json"

# Environment variable issues
# Check if all required env vars are set in Cloudflare Pages settings
```

### Issue 3: Routing Issues for SPAs

**Solution:**

```javascript
// Create _redirects file in public folder
// public/_redirects
/*    /index.html   200

// Or configure in Cloudflare Pages settings
# Redirect Rules
Source: /*
Destination: /index.html
Status: 200
```

## 📊 Performance Optimization

### Bundle Analysis

Monitor your build performance:

```bash
# Install bundle analyzer
npm install --save-dev webpack-bundle-analyzer

# Add to package.json
"analyze": "npm run build && npx webpack-bundle-analyzer build/static/js/*.js"
```

### Cloudflare-Specific Optimizations

```javascript
// Enable Cloudflare optimizations in Pages settings
- Auto Minify: CSS, JavaScript, HTML
- Brotli Compression: Enabled
- Always Use HTTPS: Enabled
- Browser Cache TTL: 4 hours
```

## 🚦 CI/CD Best Practices

### Automated Testing Before Deployment

```yaml
# .github/workflows/test.yml
name: Test before deploy
on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage --watchAll=false
      - run: npm run build
```

### Preview Deployments

Cloudflare automatically creates preview deployments for:

- Pull requests
- Non-production branches
- Manual deployments

Each preview gets a unique URL: `https://[commit-hash].your-project.pages.dev`

## 🔒 Security Considerations

### Environment Variables Security

```javascript
// ✅ Safe for React (public)
REACT_APP_API_URL=https://api.example.com
REACT_APP_APP_NAME=MyApp

// ❌ Never expose sensitive data
REACT_APP_SECRET_KEY=never-do-this
REACT_APP_PRIVATE_API_KEY=also-never-do-this
```

### Content Security Policy

```javascript
// _headers file
/*
  Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:;
```

## 📈 Monitoring and Analytics

### Cloudflare Analytics

Monitor your deployment through:

- Real-time traffic analytics
- Performance metrics
- Error tracking
- Geographic distribution

### Custom Monitoring

```javascript
// Add performance monitoring to your React app
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

function sendToAnalytics(metric) {
  // Send to your analytics service
  console.log(metric);
}

getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);
```

## 🎉 Conclusion

Deploying React applications from private repositories to Cloudflare Pages is straightforward once you understand the permission model and configuration options. The platform offers excellent performance, security, and developer experience for modern web applications.

### Key Takeaways:

- **Permissions are crucial**: Ensure proper GitHub organization access
- **Build configuration matters**: Optimize for production deployments
- **Use preview deployments**: Test changes before they go live
- **Monitor performance**: Leverage Cloudflare's analytics tools
- **Security first**: Never expose sensitive data in client-side code

### Next Steps:

1. Set up automated testing workflows
2. Configure custom domains and SSL
3. Implement performance monitoring
4. Explore Cloudflare Functions for backend functionality

With Cloudflare Pages, your React applications can achieve global scale with minimal configuration while maintaining the security of private repositories.

---

_Happy deploying! 🚀_

**Useful Links:**

- [Cloudflare Pages Documentation](https://developers.cloudflare.com/pages/)
- [React Deployment Best Practices](https://create-react-app.dev/docs/deployment/)
- [GitHub Apps Permissions Guide](https://docs.github.com/en/developers/apps/managing-github-apps/editing-a-github-apps-permissions)

---

## Digital Ocean Mastery Part 1: Setting Up Your Droplet and Storage

Learn how to create and configure a Digital Ocean droplet with attached storage for production-ready applications. Complete guide with security best practices.

- Canonical page: https://joshua-ansah.vercel.app/blog/digital-ocean-part-1-droplet-storage-setup
- Author: Joshua Ansah
- Published: September 18, 2025
- Category: DevOps
- Topics: Digital Ocean, Droplet, Storage, Linux, Ubuntu, VPS

Welcome to the first part of our comprehensive Digital Ocean mastery series! In this guide, we'll walk through creating and configuring a production-ready Digital Ocean droplet with attached storage. This foundation will serve as the backbone for all subsequent parts of our series.

## 🎯 What You'll Learn

By the end of this tutorial, you'll have:

- A properly configured Digital Ocean droplet
- Attached block storage for data persistence
- Essential security configurations
- SSH key authentication
- Firewall rules and basic hardening
- Monitoring and backup setup

## 📋 Prerequisites

Before we begin, ensure you have:

- A Digital Ocean account ([Sign up here](https://www.digitalocean.com/))
- SSH key pair generated on your local machine
- Basic command line knowledge
- A domain name (optional, for later parts)

## 🚀 Step 1: Creating Your Droplet

### Choose Your Droplet Configuration

Log into your Digital Ocean dashboard and click **"Create"** → **"Droplet"**.

```bash
# Recommended configuration for production:
Distribution: Ubuntu 22.04 (LTS) x64
Plan: Basic
CPU Options: Regular Intel - $12/month (2 GB RAM, 1 vCPU, 50 GB SSD)
Datacenter: Choose closest to your users
Authentication: SSH Key (we'll set this up)
```

### Generate SSH Keys (If You Haven't Already)

On your local machine:

```bash
# Generate a new SSH key pair
ssh-keygen -t ed25519 -C "your_email@example.com"

# Start the ssh-agent
eval "$(ssh-agent -s)"

# Add your SSH private key to the ssh-agent
ssh-add ~/.ssh/id_ed25519

# Copy the public key to clipboard (macOS)
pbcopy < ~/.ssh/id_ed25519.pub

# On Linux, use:
cat ~/.ssh/id_ed25519.pub
```

### Configure SSH Key in Digital Ocean

1. In the droplet creation form, click **"New SSH Key"**
2. Paste your public key
3. Give it a meaningful name like "My-MacBook-Pro"
4. Click **"Add SSH Key"**

### Droplet Naming and Tags

```bash
# Choose a descriptive name
Hostname: production-server-01

# Add useful tags
Tags: production, nodejs, api, web-server
```

## 💾 Step 2: Adding Block Storage

### Create a Volume

Before finishing droplet creation:

```bash
# In the "Add block storage" section:
Volume Name: app-data-volume
Size: 100 GB (adjust based on your needs)
```

**Why Block Storage?**

- Data persists even if droplet is destroyed
- Can be resized without downtime
- Separate billing from compute resources
- Easy backup and snapshot management

### Complete Droplet Creation

Click **"Create Droplet"** and wait 2-3 minutes for provisioning.

## 🔧 Step 3: Initial Server Configuration

### Connect to Your Droplet

```bash
# Get your droplet's IP from the Digital Ocean dashboard
ssh root@YOUR_DROPLET_IP

# You should see something like:
# Welcome to Ubuntu 22.04.3 LTS (GNU/Linux 5.15.0-78-generic x86_64)
```

### Update System Packages

```bash
# Update package index
apt update

# Upgrade installed packages
apt upgrade -y

# Install essential packages
apt install -y curl wget git htop unzip software-properties-common ufw fail2ban
```

### Create a Non-Root User

```bash
# Create a new user (replace 'deploy' with your preferred username)
adduser deploy

# Add user to sudo group
usermod -aG sudo deploy

# Copy SSH keys to the new user
rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
```

## 🔒 Step 4: Security Configuration

### Configure UFW Firewall

```bash
# Set default policies
ufw default deny incoming
ufw default allow outgoing

# Allow SSH (port 22)
ufw allow ssh

# Allow HTTP and HTTPS (for web applications)
ufw allow 'Nginx Full'

# Or if using specific ports:
ufw allow 80/tcp
ufw allow 443/tcp

# Enable firewall
ufw enable

# Check status
ufw status verbose
```

### Configure Fail2Ban

```bash
# Create a local configuration file
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Edit the configuration
nano /etc/fail2ban/jail.local
```

Add this configuration:

```ini
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
```

```bash
# Restart and enable fail2ban
systemctl restart fail2ban
systemctl enable fail2ban

# Check status
fail2ban-client status
```

### Disable Root Login (Optional but Recommended)

```bash
# Edit SSH configuration
nano /etc/ssh/sshd_config

# Find and modify these lines:
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes

# Restart SSH service
systemctl restart ssh
```

**⚠️ Warning**: Test SSH connection with your new user before logging out as root!

```bash
# From another terminal, test connection:
ssh deploy@YOUR_DROPLET_IP
```

## 💿 Step 5: Configuring Block Storage

### Mount the Volume

```bash
# Check if volume is attached
lsblk

# You should see something like:
# sda      8:0    0   50G  0 disk
# └─sda1   8:1    0   49G  0 part /
# sdb      8:16   0  100G  0 disk    # This is your volume

# Format the volume (only do this once!)
mkfs.ext4 /dev/sdb

# Create mount point
mkdir -p /mnt/app-data

# Mount the volume
mount /dev/sdb /mnt/app-data

# Set permissions
chown deploy:deploy /mnt/app-data
```

### Configure Automatic Mounting

```bash
# Get the UUID of your volume
blkid /dev/sdb

# Add to fstab for automatic mounting
echo 'UUID=your-uuid-here /mnt/app-data ext4 defaults,nofail,discard 0 2' >> /etc/fstab

# Test the fstab entry
umount /mnt/app-data
mount -a

# Verify it's mounted
df -h
```

### Create Application Directories

```bash
# Switch to deploy user
su - deploy

# Create application structure
mkdir -p /mnt/app-data/{apps,databases,logs,backups}
mkdir -p /mnt/app-data/apps/{production,staging,development}

# Create symlinks for easier access
ln -s /mnt/app-data ~/app-data
```

## 📊 Step 6: Monitoring and Logging Setup

### Install and Configure Log Rotation

```bash
# Create logrotate configuration for your apps
sudo nano /etc/logrotate.d/app-logs
```

```bash
/mnt/app-data/logs/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    copytruncate
}
```

### Basic System Monitoring

```bash
# Install htop for system monitoring
sudo apt install htop

# Create a simple monitoring script
nano ~/monitor.sh
```

```bash
#!/bin/bash
echo "=== System Status ==="
echo "Date: $(date)"
echo "Uptime: $(uptime)"
echo "Disk Usage:"
df -h
echo "Memory Usage:"
free -h
echo "Top Processes:"
ps aux --sort=-%cpu | head -10
```

```bash
# Make it executable
chmod +x ~/monitor.sh

# Run it
./monitor.sh
```

## 🔄 Step 7: Backup Configuration

### Create Backup Scripts

```bash
# Create backup directory
mkdir -p /mnt/app-data/backups

# Create a simple backup script
nano ~/backup.sh
```

```bash
#!/bin/bash
BACKUP_DIR="/mnt/app-data/backups"
DATE=$(date +%Y%m%d_%H%M%S)

# Create backup directory for today
mkdir -p "$BACKUP_DIR/$DATE"

# Backup important configuration files
tar -czf "$BACKUP_DIR/$DATE/system-config.tar.gz" \
    /etc/nginx \
    /etc/ssl \
    /etc/fail2ban \
    /etc/ufw \
    2>/dev/null

echo "Backup completed: $BACKUP_DIR/$DATE"

# Keep only last 7 days of backups
find "$BACKUP_DIR" -type d -mtime +7 -exec rm -rf {} +
```

```bash
# Make it executable
chmod +x ~/backup.sh

# Add to crontab for daily backups
crontab -e

# Add this line for daily backups at 2 AM:
0 2 * * * /home/deploy/backup.sh
```

## 🏷️ Step 8: Digital Ocean Features Setup

### Enable Monitoring

1. Go to your droplet in the Digital Ocean dashboard
2. Click **"Monitoring"** tab
3. Enable **"Monitoring Agent"**

### Configure Automatic Backups

```bash
# In Digital Ocean dashboard:
1. Go to your droplet
2. Click "Backups" tab
3. Enable weekly backups
```

### Set up Volume Snapshots

```bash
# Create your first volume snapshot
1. Go to "Volumes" in your Digital Ocean dashboard
2. Click your volume name
3. Click "Take Snapshot"
4. Name it: "initial-setup-snapshot"
```

## ✅ Step 9: Verification and Testing

### Test Your Setup

```bash
# Check disk space
df -h

# Check memory usage
free -h

# Check running services
systemctl status ufw fail2ban

# Test firewall
ufw status

# Check mounted volumes
mount | grep app-data

# Verify backup script
./backup.sh
ls -la /mnt/app-data/backups/
```

### Document Your Configuration

Create a configuration file for future reference:

```bash
nano ~/server-info.txt
```

```text
=== Server Configuration ===
Droplet IP: YOUR_DROPLET_IP
SSH User: deploy
SSH Key: ~/.ssh/id_ed25519

=== Storage ===
Block Storage: /dev/sdb mounted at /mnt/app-data
Size: 100GB
UUID: your-volume-uuid

=== Security ===
Firewall: UFW enabled
Fail2Ban: Configured
Root Login: Disabled
SSH Keys: Only authentication method

=== Backup ===
Daily backups: 2 AM via cron
Backup location: /mnt/app-data/backups
Retention: 7 days
```

## 🎉 What's Next?

Congratulations! You now have a production-ready Digital Ocean droplet with:

✅ **Secure Configuration**: SSH keys, firewall, fail2ban  
✅ **Persistent Storage**: 100GB block storage mounted and configured  
✅ **Monitoring**: Basic monitoring and logging setup  
✅ **Backup Strategy**: Automated daily backups  
✅ **User Management**: Non-root user with sudo access

### Coming Up in Part 2

In the next part of our series, we'll:

- Install and configure PostgreSQL
- Set up database security and user management
- Configure remote access to your database
- Implement database backup strategies
- Optimize PostgreSQL for production use

## 🔗 Quick Reference Commands

```bash
# Connect to your droplet
ssh deploy@YOUR_DROPLET_IP

# Check system status
htop
df -h
free -h

# View logs
sudo tail -f /var/log/auth.log
sudo fail2ban-client status

# Mount volume (if needed)
sudo mount /dev/sdb /mnt/app-data

# Run backup
./backup.sh
```

## 💡 Pro Tips

1. **Always test SSH access** with your new user before disabling root login
2. **Take snapshots** before major changes
3. **Monitor disk usage** regularly, especially on the root partition
4. **Keep your SSH keys secure** and backed up
5. **Document everything** for your future self and team members

---

_Ready for Part 2? We'll dive into PostgreSQL setup and configuration!_

**Next**: [Digital Ocean Mastery Part 2: PostgreSQL Setup and External Access](/blog/digital-ocean-part-2-postgresql-setup)

---

## Digital Ocean Mastery Part 2: PostgreSQL Setup and External Access

Install and configure PostgreSQL on your Digital Ocean droplet with secure external access. Learn database security, user management, and remote connections.

- Canonical page: https://joshua-ansah.vercel.app/blog/digital-ocean-part-2-postgresql-setup
- Author: Joshua Ansah
- Published: September 17, 2025
- Category: DevOps
- Topics: PostgreSQL, Database, Digital Ocean, Security, Remote Access

Welcome to Part 2 of our Digital Ocean mastery series! Building on our properly configured droplet from Part 1, we'll now install and configure PostgreSQL with secure external access. This setup will serve as the database foundation for our applications.

## 🎯 What You'll Learn

In this comprehensive guide, we'll cover:

- PostgreSQL installation and initial configuration
- Creating databases and users
- Configuring secure remote access
- Setting up SSL connections
- Database backup and restoration
- Performance optimization basics
- Security best practices

## 📋 Prerequisites

Before starting, ensure you have:

- Completed [Part 1](/blog/digital-ocean-part-1-droplet-storage-setup) of this series
- SSH access to your Digital Ocean droplet
- Basic SQL knowledge
- A database client (pgAdmin, DBeaver, or command line tools)

## 🗄️ Step 1: Installing PostgreSQL

### Update System and Install PostgreSQL

```bash
# Connect to your droplet
ssh deploy@YOUR_DROPLET_IP

# Update package index
sudo apt update

# Install PostgreSQL and additional tools
sudo apt install -y postgresql postgresql-contrib postgresql-client

# Check installation
sudo systemctl status postgresql
```

### Verify Installation

```bash
# Check PostgreSQL version
sudo -u postgres psql -c "SELECT version();"

# Check if service is running
sudo systemctl is-active postgresql
sudo systemctl is-enabled postgresql
```

## 🔧 Step 2: Initial PostgreSQL Configuration

### Switch to PostgreSQL User

```bash
# Switch to postgres user
sudo -i -u postgres

# Access PostgreSQL prompt
psql

# You should see:
# postgres=#
```

### Set PostgreSQL Admin Password

```sql
-- Set password for postgres user
ALTER USER postgres PASSWORD 'your_secure_password_here';

-- Exit PostgreSQL
\q
```

```bash
# Exit postgres user session
exit
```

### Configure PostgreSQL Data Directory on Block Storage

```bash
# Stop PostgreSQL service
sudo systemctl stop postgresql

# Create PostgreSQL directory on our block storage
sudo mkdir -p /mnt/app-data/databases/postgresql

# Move existing data directory
sudo mv /var/lib/postgresql/14/main /mnt/app-data/databases/postgresql/

# Create symlink to new location
sudo ln -s /mnt/app-data/databases/postgresql/main /var/lib/postgresql/14/main

# Set proper ownership
sudo chown -R postgres:postgres /mnt/app-data/databases/postgresql
sudo chown -R postgres:postgres /var/lib/postgresql/14/main

# Start PostgreSQL
sudo systemctl start postgresql
```

## 🔐 Step 3: Creating Application Database and User

### Create Application Database

```bash
# Switch to postgres user
sudo -i -u postgres

# Create a new database for your application
createdb myapp_production

# Create a dedicated user for your application
psql
```

```sql
-- Create application user with limited privileges
CREATE USER myapp_user WITH PASSWORD 'secure_app_password';

-- Grant privileges to the application database
GRANT CONNECT ON DATABASE myapp_production TO myapp_user;
GRANT USAGE ON SCHEMA public TO myapp_user;
GRANT CREATE ON SCHEMA public TO myapp_user;

-- For existing tables (if any)
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO myapp_user;

-- For future tables
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO myapp_user;

-- For sequences (auto-increment fields)
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO myapp_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO myapp_user;

-- Verify user creation
\du

-- Exit PostgreSQL
\q
exit
```

## 🌐 Step 4: Configuring Remote Access

### Configure PostgreSQL to Accept Connections

```bash
# Edit PostgreSQL configuration
sudo nano /etc/postgresql/14/main/postgresql.conf
```

Find and modify these settings:

```bash
# Listen on all addresses
listen_addresses = '*'

# Increase max connections if needed
max_connections = 200

# Enable logging for security
log_connections = on
log_disconnections = on
log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h '

# Performance settings (adjust based on your droplet size)
shared_buffers = 512MB
effective_cache_size = 1GB
work_mem = 4MB
maintenance_work_mem = 64MB
```

### Configure Client Authentication

```bash
# Edit pg_hba.conf for authentication rules
sudo nano /etc/postgresql/14/main/pg_hba.conf
```

Add these lines at the end (be careful with the order):

```bash
# Application connections
host    myapp_production    myapp_user      0.0.0.0/0               md5

# Allow postgres user from specific IPs only (replace with your IPs)
host    all                 postgres        YOUR_LOCAL_IP/32        md5
host    all                 postgres        YOUR_OFFICE_IP/32       md5

# Deny all other connections
host    all                 all             0.0.0.0/0               reject
```

**Security Note**: Replace `YOUR_LOCAL_IP` and `YOUR_OFFICE_IP` with actual IP addresses. Never use `0.0.0.0/0` for the postgres user.

### Configure Firewall for PostgreSQL

```bash
# Allow PostgreSQL port (5432) through firewall
sudo ufw allow 5432/tcp

# Check firewall status
sudo ufw status
```

### Restart PostgreSQL

```bash
# Restart PostgreSQL to apply configuration changes
sudo systemctl restart postgresql

# Check if it's running
sudo systemctl status postgresql
```

## 🔒 Step 5: Setting Up SSL Connections

### Generate SSL Certificates

```bash
# Create SSL directory
sudo mkdir -p /mnt/app-data/databases/postgresql/ssl
cd /mnt/app-data/databases/postgresql/ssl

# Generate private key
sudo openssl genrsa -out server.key 2048

# Generate certificate signing request
sudo openssl req -new -key server.key -out server.csr

# Generate self-signed certificate (for production, use a proper CA)
sudo openssl x509 -req -in server.csr -signkey server.key -out server.crt -days 365

# Set proper permissions
sudo chown postgres:postgres server.key server.crt server.csr
sudo chmod 600 server.key
sudo chmod 644 server.crt
```

### Configure PostgreSQL for SSL

```bash
# Edit PostgreSQL configuration
sudo nano /etc/postgresql/14/main/postgresql.conf
```

Add these SSL settings:

```bash
# SSL Configuration
ssl = on
ssl_cert_file = '/mnt/app-data/databases/postgresql/ssl/server.crt'
ssl_key_file = '/mnt/app-data/databases/postgresql/ssl/server.key'
ssl_prefer_server_ciphers = on
```

### Update pg_hba.conf for SSL

```bash
# Edit authentication file
sudo nano /etc/postgresql/14/main/pg_hba.conf
```

Update the connection rules to require SSL:

```bash
# SSL-only connections for application
hostssl myapp_production    myapp_user      0.0.0.0/0               md5

# SSL-only for postgres user
hostssl all                 postgres        YOUR_LOCAL_IP/32        md5
hostssl all                 postgres        YOUR_OFFICE_IP/32       md5
```

```bash
# Restart PostgreSQL
sudo systemctl restart postgresql
```

## 🧪 Step 6: Testing Remote Connections

### Test from Droplet (Local Connection)

```bash
# Test local connection
psql -h localhost -U myapp_user -d myapp_production

# Test with SSL
psql "host=localhost user=myapp_user dbname=myapp_production sslmode=require"
```

### Test from Your Local Machine

```bash
# Install PostgreSQL client on your local machine (if not already installed)
# macOS:
brew install postgresql

# Ubuntu/Debian:
sudo apt install postgresql-client

# Test remote connection
psql -h YOUR_DROPLET_IP -U myapp_user -d myapp_production

# Test with SSL
psql "host=YOUR_DROPLET_IP user=myapp_user dbname=myapp_production sslmode=require"
```

### Connection String Examples

For application configuration:

```bash
# Standard connection string
postgresql://myapp_user:password@YOUR_DROPLET_IP:5432/myapp_production

# SSL connection string
postgresql://myapp_user:password@YOUR_DROPLET_IP:5432/myapp_production?sslmode=require

# Node.js example
DATABASE_URL=postgresql://myapp_user:password@YOUR_DROPLET_IP:5432/myapp_production?sslmode=require
```

## 📦 Step 7: Database Backup and Restoration

### Create Backup Scripts

```bash
# Create backup directory
mkdir -p /mnt/app-data/backups/postgresql

# Create backup script
nano ~/pg_backup.sh
```

```bash
#!/bin/bash

# Configuration
DB_NAME="myapp_production"
DB_USER="myapp_user"
BACKUP_DIR="/mnt/app-data/backups/postgresql"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_backup_$DATE.sql"

# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"

# Create backup
echo "Starting backup of $DB_NAME..."
PGPASSWORD='secure_app_password' pg_dump -h localhost -U "$DB_USER" -d "$DB_NAME" > "$BACKUP_FILE"

# Compress backup
gzip "$BACKUP_FILE"

echo "Backup completed: ${BACKUP_FILE}.gz"

# Keep only last 7 days of backups
find "$BACKUP_DIR" -name "*.gz" -mtime +7 -delete

# Log backup
echo "$(date): Backup completed for $DB_NAME" >> "$BACKUP_DIR/backup.log"
```

```bash
# Make script executable
chmod +x ~/pg_backup.sh

# Test backup
./pg_backup.sh
```

### Automate Backups

```bash
# Add to crontab
crontab -e

# Add this line for daily backups at 3 AM:
0 3 * * * /home/deploy/pg_backup.sh
```

### Restoration Script

```bash
# Create restoration script
nano ~/pg_restore.sh
```

```bash
#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 <backup_file.sql.gz>"
    echo "Available backups:"
    ls -la /mnt/app-data/backups/postgresql/
    exit 1
fi

BACKUP_FILE=$1
DB_NAME="myapp_production"
DB_USER="myapp_user"

# Check if backup file exists
if [ ! -f "$BACKUP_FILE" ]; then
    echo "Backup file not found: $BACKUP_FILE"
    exit 1
fi

echo "WARNING: This will replace all data in $DB_NAME!"
read -p "Are you sure? (yes/no): " confirm

if [ "$confirm" = "yes" ]; then
    echo "Restoring from $BACKUP_FILE..."

    # Drop and recreate database (be very careful!)
    sudo -u postgres dropdb "$DB_NAME"
    sudo -u postgres createdb "$DB_NAME"
    sudo -u postgres psql -c "GRANT CONNECT ON DATABASE $DB_NAME TO $DB_USER;"

    # Restore backup
    if [[ "$BACKUP_FILE" == *.gz ]]; then
        gunzip -c "$BACKUP_FILE" | PGPASSWORD='secure_app_password' psql -h localhost -U "$DB_USER" -d "$DB_NAME"
    else
        PGPASSWORD='secure_app_password' psql -h localhost -U "$DB_USER" -d "$DB_NAME" < "$BACKUP_FILE"
    fi

    echo "Restoration completed!"
else
    echo "Restoration cancelled."
fi
```

```bash
# Make restoration script executable
chmod +x ~/pg_restore.sh
```

## ⚡ Step 8: Performance Optimization

### Configure PostgreSQL for Your Droplet Size

Based on a 2GB RAM droplet, edit PostgreSQL configuration:

```bash
sudo nano /etc/postgresql/14/main/postgresql.conf
```

```bash
# Memory settings for 2GB RAM droplet
shared_buffers = 512MB
effective_cache_size = 1GB
work_mem = 4MB
maintenance_work_mem = 128MB

# Connection settings
max_connections = 100

# Checkpoint settings
checkpoint_completion_target = 0.9
wal_buffers = 16MB

# Query planner settings
random_page_cost = 1.1
effective_io_concurrency = 200

# Logging for performance monitoring
log_min_duration_statement = 1000  # Log queries taking longer than 1 second
log_checkpoints = on
log_connections = on
log_disconnections = on
```

### Create Performance Monitoring Script

```bash
nano ~/pg_monitor.sh
```

```bash
#!/bin/bash
echo "=== PostgreSQL Status ==="
echo "Date: $(date)"
echo

echo "=== Active Connections ==="
sudo -u postgres psql -c "SELECT count(*) as active_connections FROM pg_stat_activity WHERE state = 'active';"

echo "=== Database Sizes ==="
sudo -u postgres psql -c "SELECT datname, pg_size_pretty(pg_database_size(datname)) as size FROM pg_database WHERE datistemplate = false;"

echo "=== Slow Queries (last hour) ==="
sudo -u postgres psql -c "SELECT query, calls, mean_exec_time FROM pg_stat_statements WHERE mean_exec_time > 1000 ORDER BY mean_exec_time DESC LIMIT 5;" 2>/dev/null || echo "pg_stat_statements not enabled"

echo "=== Cache Hit Ratio ==="
sudo -u postgres psql -c "SELECT 'index hit rate' as name, (sum(idx_blks_hit)) / nullif(sum(idx_blks_hit + idx_blks_read),0) as ratio FROM pg_statio_user_indexes UNION ALL SELECT 'table hit rate' as name, sum(heap_blks_hit) / nullif(sum(heap_blks_hit) + sum(heap_blks_read),0) as ratio FROM pg_statio_user_tables;"
```

```bash
chmod +x ~/pg_monitor.sh
```

## 🔐 Step 9: Advanced Security Configuration

### Enable Query Logging for Security

```bash
sudo nano /etc/postgresql/14/main/postgresql.conf
```

```bash
# Security logging
log_statement = 'mod'  # Log all INSERT, UPDATE, DELETE statements
log_min_duration_statement = 0  # Log all statements (set to -1 to disable)
log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h '
```

### Create Database Monitoring User

```bash
sudo -i -u postgres
psql
```

```sql
-- Create monitoring user with limited privileges
CREATE USER db_monitor WITH PASSWORD 'monitor_password';

-- Grant necessary permissions for monitoring
GRANT CONNECT ON DATABASE myapp_production TO db_monitor;
GRANT USAGE ON SCHEMA public TO db_monitor;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO db_monitor;

-- For system monitoring
GRANT SELECT ON ALL TABLES IN SCHEMA information_schema TO db_monitor;
GRANT SELECT ON ALL TABLES IN SCHEMA pg_catalog TO db_monitor;

\q
exit
```

### Configure Connection Limits

```sql
-- Limit connections per user
ALTER USER myapp_user CONNECTION LIMIT 20;
ALTER USER db_monitor CONNECTION LIMIT 5;
```

## ✅ Step 10: Verification and Testing

### Comprehensive Testing Script

```bash
nano ~/test_postgresql.sh
```

```bash
#!/bin/bash

echo "=== PostgreSQL Configuration Test ==="

# Test 1: Service status
echo "1. Service Status:"
sudo systemctl is-active postgresql

# Test 2: Local connection
echo "2. Local Connection Test:"
PGPASSWORD='secure_app_password' psql -h localhost -U myapp_user -d myapp_production -c "SELECT 'Local connection successful' as test;"

# Test 3: SSL connection
echo "3. SSL Connection Test:"
PGPASSWORD='secure_app_password' psql "host=localhost user=myapp_user dbname=myapp_production sslmode=require" -c "SELECT 'SSL connection successful' as test;"

# Test 4: Create and query test table
echo "4. Database Operations Test:"
PGPASSWORD='secure_app_password' psql -h localhost -U myapp_user -d myapp_production -c "
CREATE TABLE IF NOT EXISTS test_table (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

INSERT INTO test_table (name) VALUES ('Test Entry');
SELECT * FROM test_table;
DROP TABLE test_table;
"

# Test 5: Backup test
echo "5. Backup Test:"
./pg_backup.sh

echo "=== All Tests Completed ==="
```

```bash
chmod +x ~/test_postgresql.sh
./test_postgresql.sh
```

## 📊 Step 11: Monitoring and Maintenance

### Set Up Log Rotation for PostgreSQL

```bash
sudo nano /etc/logrotate.d/postgresql
```

```bash
/var/log/postgresql/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    copytruncate
    su postgres postgres
}
```

### Create Maintenance Script

```bash
nano ~/pg_maintenance.sh
```

```bash
#!/bin/bash

echo "Starting PostgreSQL maintenance..."

# Vacuum and analyze all databases
sudo -u postgres psql -c "VACUUM ANALYZE;"

# Reindex if needed (run weekly)
if [ "$(date +%u)" -eq 7 ]; then
    echo "Weekly reindex..."
    sudo -u postgres psql -d myapp_production -c "REINDEX DATABASE myapp_production;"
fi

# Update statistics
sudo -u postgres psql -c "ANALYZE;"

echo "Maintenance completed at $(date)"
```

```bash
chmod +x ~/pg_maintenance.sh

# Add to crontab for weekly maintenance
crontab -e

# Add this line for weekly maintenance on Sunday at 2 AM:
0 2 * * 0 /home/deploy/pg_maintenance.sh
```

## 🎉 What You've Accomplished

Congratulations! You now have a production-ready PostgreSQL setup with:

✅ **Secure Installation**: PostgreSQL installed on block storage  
✅ **Remote Access**: Secure SSL connections from external clients  
✅ **User Management**: Dedicated application user with limited privileges  
✅ **Backup Strategy**: Automated daily backups with 7-day retention  
✅ **Performance Optimization**: Tuned for your droplet size  
✅ **Security Hardening**: SSL, logging, and connection limits  
✅ **Monitoring**: Scripts for performance and health monitoring

### Connection Information Summary

```bash
# Application Connection String
postgresql://myapp_user:secure_app_password@YOUR_DROPLET_IP:5432/myapp_production?sslmode=require

# Admin Connection (from allowed IPs only)
postgresql://postgres:your_secure_password_here@YOUR_DROPLET_IP:5432/postgres?sslmode=require

# Database Files Location
/mnt/app-data/databases/postgresql/main

# Backups Location
/mnt/app-data/backups/postgresql
```

## 🔗 Quick Reference Commands

```bash
# Connect to database
PGPASSWORD='password' psql -h YOUR_DROPLET_IP -U myapp_user -d myapp_production

# Check PostgreSQL status
sudo systemctl status postgresql

# View PostgreSQL logs
sudo tail -f /var/log/postgresql/postgresql-14-main.log

# Run backup
./pg_backup.sh

# Monitor performance
./pg_monitor.sh

# Maintenance
./pg_maintenance.sh
```

## 🔮 Coming Up in Part 3

In the next part of our series, we'll:

- Install and configure Docker
- Set up Docker Compose for application management
- Create containerized environments
- Implement container networking
- Configure persistent volumes for containers

---

_Ready to containerize your applications? Let's move on to Docker!_

**Next**: [Digital Ocean Mastery Part 3: Docker Installation and Configuration](/blog/digital-ocean-part-3-docker-installation)

---

## Digital Ocean Mastery Part 3: Docker Installation and Configuration

Master Docker installation on Digital Ocean droplets. Learn containerization best practices, Docker Compose, and container management for production environments.

- Canonical page: https://joshua-ansah.vercel.app/blog/digital-ocean-part-3-docker-installation
- Author: Joshua Ansah
- Published: September 16, 2025
- Category: DevOps
- Topics: Docker, Containers, Digital Ocean, Docker Compose, Containerization

Welcome to Part 3 of our Digital Ocean mastery series! Building upon our secure droplet and PostgreSQL setup, we'll now install and configure Docker for containerized application deployment. This foundation will enable us to deploy scalable, isolated applications efficiently.

## 🎯 What You'll Learn

In this comprehensive guide, we'll cover:

- Docker installation and configuration on Ubuntu
- Docker Compose setup and best practices
- Container networking and volume management
- Security configurations for production
- Multi-environment container management
- Monitoring and logging for containerized applications
- Docker registry setup and management

## 📋 Prerequisites

Before starting, ensure you have:

- Completed [Part 1](/blog/digital-ocean-part-1-droplet-storage-setup) and [Part 2](/blog/digital-ocean-part-2-postgresql-setup)
- SSH access to your Digital Ocean droplet
- Basic understanding of containerization concepts
- Familiarity with YAML syntax (for Docker Compose)

## 🐳 Step 1: Installing Docker

### Remove Old Docker Versions

```bash
# Connect to your droplet
ssh deploy@YOUR_DROPLET_IP

# Remove any old Docker installations
sudo apt remove docker docker-engine docker.io containerd runc
```

### Install Docker Using Official Repository

```bash
# Update package index
sudo apt update

# Install required packages
sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release

# Add Docker's official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Add Docker repository
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Update package index again
sudo apt update

# Install Docker Engine
sudo apt install -y docker-ce docker-ce-cli containerd.io
```

### Verify Docker Installation

```bash
# Check Docker version
docker --version

# Check if Docker service is running
sudo systemctl status docker

# Run hello-world container
sudo docker run hello-world
```

## 👥 Step 2: Docker User Configuration

### Add User to Docker Group

```bash
# Add current user to docker group
sudo usermod -aG docker $USER

# Apply group changes (or logout and login again)
newgrp docker

# Test Docker without sudo
docker run hello-world
```

### Configure Docker to Start on Boot

```bash
# Enable Docker service
sudo systemctl enable docker

# Verify it's enabled
sudo systemctl is-enabled docker
```

## 🐙 Step 3: Installing Docker Compose

### Install Docker Compose

```bash
# Get latest version number (or specify a version)
DOCKER_COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep 'tag_name' | cut -d\" -f4)

# Download Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

# Make it executable
sudo chmod +x /usr/local/bin/docker-compose

# Create symlink for easier access
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

# Verify installation
docker-compose --version
```

## 📁 Step 4: Docker Directory Structure Setup

### Create Docker Project Structure

```bash
# Create Docker directories on block storage
mkdir -p /mnt/app-data/docker/{
    containers,
    volumes,
    networks,
    configs,
    logs,
    registry
}

# Create environment-specific directories
mkdir -p /mnt/app-data/docker/containers/{production,staging,development}

# Create symlink for easier access
ln -s /mnt/app-data/docker ~/docker

# Set up volume directories
mkdir -p /mnt/app-data/docker/volumes/{postgres-data,app-logs,nginx-conf,ssl-certs}
```

### Configure Docker Data Directory

```bash
# Create Docker daemon configuration
sudo mkdir -p /etc/docker

sudo tee /etc/docker/daemon.json > /dev/null <<EOF
{
    "data-root": "/mnt/app-data/docker",
    "storage-driver": "overlay2",
    "log-driver": "json-file",
    "log-opts": {
        "max-size": "10m",
        "max-file": "3"
    },
    "default-ulimits": {
        "nofile": {
            "Name": "nofile",
            "Hard": 64000,
            "Soft": 64000
        }
    }
}
EOF

# Restart Docker to apply changes
sudo systemctl restart docker

# Verify new data directory
docker info | grep "Docker Root Dir"
```

## 🔒 Step 5: Docker Security Configuration

### Configure Docker Security Options

```bash
# Edit Docker daemon configuration for security
sudo nano /etc/docker/daemon.json
```

Update with security settings:

```json
{
  "data-root": "/mnt/app-data/docker",
  "storage-driver": "overlay2",
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 64000,
      "Soft": 64000
    }
  },
  "userns-remap": "default",
  "no-new-privileges": true,
  "seccomp-profile": "/etc/docker/seccomp.json",
  "apparmor-profile": "docker-default"
}
```

### Configure User Namespace Remapping

```bash
# Create subuid and subgid entries
echo "dockremap:165536:65536" | sudo tee -a /etc/subuid
echo "dockremap:165536:65536" | sudo tee -a /etc/subgid

# Restart Docker
sudo systemctl restart docker
```

### Create Security Profiles

```bash
# Download default seccomp profile
sudo curl -L https://raw.githubusercontent.com/moby/moby/master/profiles/seccomp/default.json -o /etc/docker/seccomp.json
```

## 🌐 Step 6: Docker Networking Configuration

### Create Custom Networks

```bash
# Create custom bridge networks for different environments
docker network create --driver bridge production-network
docker network create --driver bridge staging-network
docker network create --driver bridge development-network

# Create an isolated network for databases
docker network create --driver bridge --internal database-network

# List networks
docker network ls
```

### Configure Network Security

```bash
# Create network configuration file
mkdir -p ~/docker/configs

cat > ~/docker/configs/network-security.yml <<EOF
# Network security configuration
networks:
  production-network:
    driver: bridge
    driver_opts:
      com.docker.network.bridge.enable_icc: "false"
      com.docker.network.bridge.enable_ip_masquerade: "true"
      com.docker.network.driver.mtu: "1500"
    ipam:
      config:
        - subnet: 172.20.0.0/16
          gateway: 172.20.0.1

  database-network:
    driver: bridge
    internal: true
    ipam:
      config:
        - subnet: 172.21.0.0/16
          gateway: 172.21.0.1
EOF
```

## 📦 Step 7: Creating Docker Compose Templates

### Basic Application Template

```bash
# Create a template for Node.js applications
cat > ~/docker/configs/nodejs-template.yml <<EOF
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: \${APP_NAME}-app
    restart: unless-stopped
    environment:
      - NODE_ENV=\${NODE_ENV}
      - DATABASE_URL=\${DATABASE_URL}
      - PORT=\${PORT}
    ports:
      - "\${PORT}:3000"
    volumes:
      - /mnt/app-data/docker/volumes/app-logs:/app/logs
      - /mnt/app-data/docker/volumes/app-uploads:/app/uploads
    networks:
      - production-network
    depends_on:
      - redis
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  redis:
    image: redis:7-alpine
    container_name: \${APP_NAME}-redis
    restart: unless-stopped
    command: redis-server --appendonly yes --requirepass \${REDIS_PASSWORD}
    volumes:
      - /mnt/app-data/docker/volumes/redis-data:/data
    networks:
      - production-network
    healthcheck:
      test: ["CMD", "redis-cli", "--raw", "incr", "ping"]
      interval: 30s
      timeout: 3s
      retries: 5

  nginx:
    image: nginx:alpine
    container_name: \${APP_NAME}-nginx
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /mnt/app-data/docker/volumes/nginx-conf:/etc/nginx/conf.d
      - /mnt/app-data/docker/volumes/ssl-certs:/etc/ssl/certs
      - /mnt/app-data/docker/volumes/nginx-logs:/var/log/nginx
    networks:
      - production-network
    depends_on:
      - app

networks:
  production-network:
    external: true

volumes:
  app-logs:
    driver: local
  redis-data:
    driver: local
  nginx-conf:
    driver: local
  ssl-certs:
    driver: local
EOF
```

### Database Connection Template

```bash
# Create PostgreSQL connection template
cat > ~/docker/configs/postgres-external.yml <<EOF
version: '3.8'

services:
  app:
    image: node:18-alpine
    container_name: \${APP_NAME}-app
    restart: unless-stopped
    environment:
      - DATABASE_URL=postgresql://\${DB_USER}:\${DB_PASSWORD}@\${DB_HOST}:5432/\${DB_NAME}?sslmode=require
    extra_hosts:
      - "host.docker.internal:host-gateway"
    networks:
      - production-network

networks:
  production-network:
    external: true
EOF
```

## 🔍 Step 8: Docker Monitoring and Logging

### Install Docker System Monitoring

```bash
# Create monitoring compose file
cat > ~/docker/configs/monitoring.yml <<EOF
version: '3.8'

services:
  portainer:
    image: portainer/portainer-ce:latest
    container_name: portainer
    restart: unless-stopped
    ports:
      - "9000:9000"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /mnt/app-data/docker/volumes/portainer-data:/data
    networks:
      - production-network

  watchtower:
    image: containrrr/watchtower
    container_name: watchtower
    restart: unless-stopped
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    environment:
      - WATCHTOWER_CLEANUP=true
      - WATCHTOWER_SCHEDULE=0 0 4 * * *
    networks:
      - production-network

networks:
  production-network:
    external: true
EOF

# Start monitoring services
cd ~/docker/configs
docker-compose -f monitoring.yml up -d
```

### Configure Container Logging

```bash
# Create logging configuration
cat > ~/docker/configs/logging.yml <<EOF
version: '3.8'

x-logging: &default-logging
  driver: "json-file"
  options:
    max-size: "10m"
    max-file: "3"
    labels: "service,environment"

services:
  app:
    image: your-app:latest
    container_name: app
    logging: *default-logging
    labels:
      - "service=app"
      - "environment=production"
EOF
```

## 🛠️ Step 9: Docker Maintenance Scripts

### Create Container Management Scripts

```bash
# Container cleanup script
cat > ~/docker-cleanup.sh <<EOF
#!/bin/bash

echo "Starting Docker cleanup..."

# Remove stopped containers
docker container prune -f

# Remove unused images
docker image prune -a -f

# Remove unused volumes
docker volume prune -f

# Remove unused networks
docker network prune -f

# Remove build cache
docker builder prune -f

# Show disk usage after cleanup
echo "Docker disk usage after cleanup:"
docker system df

echo "Cleanup completed at \$(date)"
EOF

chmod +x ~/docker-cleanup.sh
```

### Docker Health Check Script

```bash
# Health monitoring script
cat > ~/docker-monitor.sh <<EOF
#!/bin/bash

echo "=== Docker System Status ==="
echo "Date: \$(date)"
echo

echo "=== Running Containers ==="
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
echo

echo "=== Container Health Status ==="
docker ps --format "table {{.Names}}\t{{.Status}}" | grep -v "NAMES"
echo

echo "=== Docker Resource Usage ==="
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}"
echo

echo "=== Docker Disk Usage ==="
docker system df
echo

echo "=== Failed Containers (if any) ==="
docker ps -a --filter "status=exited" --filter "status=dead" --format "table {{.Names}}\t{{.Status}}\t{{.CreatedAt}}"
EOF

chmod +x ~/docker-monitor.sh
```

### Backup Script for Docker Volumes

```bash
# Docker backup script
cat > ~/docker-backup.sh <<EOF
#!/bin/bash

BACKUP_DIR="/mnt/app-data/backups/docker"
DATE=\$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p "\$BACKUP_DIR"

echo "Starting Docker backup..."

# Backup Docker volumes
docker run --rm -v /mnt/app-data/docker/volumes:/source -v "\$BACKUP_DIR:/backup" alpine tar czf "/backup/docker-volumes-\$DATE.tar.gz" -C /source .

# Backup Docker configurations
tar czf "\$BACKUP_DIR/docker-configs-\$DATE.tar.gz" -C ~/docker configs

# List containers and their configurations
docker ps -a --format "{{.Names}}\t{{.Image}}\t{{.Status}}" > "\$BACKUP_DIR/containers-\$DATE.txt"

# Export Docker images (for critical custom images)
# docker save your-custom-image:latest | gzip > "\$BACKUP_DIR/custom-image-\$DATE.tar.gz"

echo "Backup completed: \$BACKUP_DIR"

# Keep only last 7 days of backups
find "\$BACKUP_DIR" -name "*.tar.gz" -mtime +7 -delete
find "\$BACKUP_DIR" -name "*.txt" -mtime +7 -delete
EOF

chmod +x ~/docker-backup.sh
```

### Automate Maintenance Tasks

```bash
# Add to crontab
crontab -e

# Add these lines:
# Daily cleanup at 2 AM
0 2 * * * /home/deploy/docker-cleanup.sh >> /mnt/app-data/docker/logs/cleanup.log 2>&1

# Daily backup at 3 AM
0 3 * * * /home/deploy/docker-backup.sh >> /mnt/app-data/docker/logs/backup.log 2>&1

# Monitor containers every 15 minutes
*/15 * * * * /home/deploy/docker-monitor.sh >> /mnt/app-data/docker/logs/monitor.log 2>&1
```

## 🔐 Step 10: Docker Registry Setup (Optional)

### Set Up Private Registry

```bash
# Create registry configuration
cat > ~/docker/configs/registry.yml <<EOF
version: '3.8'

services:
  registry:
    image: registry:2
    container_name: docker-registry
    restart: unless-stopped
    ports:
      - "5000:5000"
    environment:
      REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY: /data
      REGISTRY_AUTH: htpasswd
      REGISTRY_AUTH_HTPASSWD_REALM: Registry Realm
      REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
    volumes:
      - /mnt/app-data/docker/registry/data:/data
      - /mnt/app-data/docker/registry/auth:/auth
    networks:
      - production-network

networks:
  production-network:
    external: true
EOF

# Create registry authentication
mkdir -p /mnt/app-data/docker/registry/auth
docker run --rm --entrypoint htpasswd httpd:2 -Bbn admin your_registry_password > /mnt/app-data/docker/registry/auth/htpasswd

# Start registry
cd ~/docker/configs
docker-compose -f registry.yml up -d
```

## 🧪 Step 11: Testing Docker Installation

### Comprehensive Test Script

```bash
# Create comprehensive test script
cat > ~/test-docker.sh <<EOF
#!/bin/bash

echo "=== Docker Installation Test ==="

# Test 1: Docker version and info
echo "1. Docker Version:"
docker --version
docker-compose --version

# Test 2: Docker service status
echo "2. Docker Service Status:"
systemctl is-active docker

# Test 3: User permissions
echo "3. User Permissions Test:"
docker run --rm hello-world

# Test 4: Network creation and management
echo "4. Network Test:"
docker network ls | grep production-network

# Test 5: Volume management
echo "5. Volume Test:"
docker volume create test-volume
docker volume ls | grep test-volume
docker volume rm test-volume

# Test 6: Container lifecycle
echo "6. Container Lifecycle Test:"
docker run -d --name test-nginx nginx:alpine
sleep 5
docker ps | grep test-nginx
docker stop test-nginx
docker rm test-nginx

# Test 7: Docker Compose
echo "7. Docker Compose Test:"
cd ~/docker/configs
docker-compose -f monitoring.yml ps

# Test 8: Resource monitoring
echo "8. Resource Usage:"
docker system df

echo "=== All Tests Completed ==="
EOF

chmod +x ~/test-docker.sh
./test-docker.sh
```

## 🎉 What You've Accomplished

Congratulations! You now have a production-ready Docker environment with:

✅ **Docker Engine**: Latest stable version installed and configured  
✅ **Docker Compose**: For multi-container application management  
✅ **Security Hardening**: User namespace remapping and security profiles  
✅ **Custom Networks**: Isolated networks for different environments  
✅ **Volume Management**: Persistent storage on block storage  
✅ **Monitoring Tools**: Portainer and Watchtower for container management  
✅ **Automated Maintenance**: Cleanup, backup, and monitoring scripts  
✅ **Private Registry**: Optional private Docker registry setup

### Key Configuration Files

```bash
# Docker daemon configuration
/etc/docker/daemon.json

# Docker data directory
/mnt/app-data/docker/

# Compose templates
~/docker/configs/

# Maintenance scripts
~/docker-cleanup.sh
~/docker-monitor.sh
~/docker-backup.sh
```

## 🔗 Quick Reference Commands

```bash
# Docker basics
docker ps                    # List running containers
docker images               # List images
docker logs <container>     # View container logs
docker exec -it <container> /bin/sh  # Enter container

# Docker Compose
docker-compose up -d        # Start services in background
docker-compose down         # Stop and remove services
docker-compose logs -f      # Follow logs
docker-compose ps           # List services

# Maintenance
./docker-cleanup.sh         # Clean up Docker resources
./docker-monitor.sh         # Monitor container health
./docker-backup.sh          # Backup volumes and configs

# Monitoring
docker stats                # Real-time resource usage
docker system df            # Disk usage
docker system events        # Docker events
```

## 💡 Best Practices Summary

1. **Resource Limits**: Always set memory and CPU limits for containers
2. **Health Checks**: Implement health checks for all services
3. **Logging**: Configure centralized logging with log rotation
4. **Security**: Use non-root users in containers when possible
5. **Networks**: Use custom networks instead of default bridge
6. **Volumes**: Store persistent data on named volumes
7. **Updates**: Regularly update base images and containers
8. **Monitoring**: Monitor container performance and health
9. **Backups**: Regular backups of volumes and configurations
10. **Documentation**: Document your container configurations

## 🔮 Coming Up in Part 4

In the next part of our series, we'll:

- Deploy a Node.js application using Docker
- Set up GitHub Actions for automated deployments
- Configure CI/CD pipelines
- Implement zero-downtime deployments
- Set up application monitoring and logging

---

_Ready to deploy your first containerized application? Let's move on to automated deployments!_

**Next**: [Digital Ocean Mastery Part 4: Node.js Deployment with GitHub Actions](/blog/digital-ocean-part-4-nodejs-github-actions)

---

## Digital Ocean Mastery Part 4: Node.js Deployment with GitHub Actions

Deploy Node.js applications to Digital Ocean using GitHub Actions CI/CD. Automate your deployment pipeline with zero-downtime deployments and monitoring.

- Canonical page: https://joshua-ansah.vercel.app/blog/digital-ocean-part-4-nodejs-github-actions
- Author: Joshua Ansah
- Published: September 15, 2025
- Category: DevOps
- Topics: Node.js, GitHub Actions, CI/CD, Digital Ocean, Deployment, Automation

Welcome to Part 4 of our Digital Ocean mastery series! Building on our containerized environment, we'll now deploy a Node.js application using GitHub Actions for automated CI/CD. This setup will enable zero-downtime deployments with comprehensive monitoring.

## 🎯 What You'll Learn

In this comprehensive guide, we'll cover:

- Setting up a Node.js application for containerized deployment
- Creating GitHub Actions workflows for CI/CD
- Implementing zero-downtime deployment strategies
- Configuring environment variables and secrets
- Setting up application monitoring and health checks
- Implementing rollback strategies
- Performance optimization and scaling

## 📋 Prerequisites

Before starting, ensure you have:

- Completed [Parts 1-3](/blog/digital-ocean-part-1-droplet-storage-setup) of this series
- A Node.js application in a GitHub repository
- Basic knowledge of Node.js and Express.js
- Understanding of Docker concepts
- GitHub account with repository access

## 🚀 Step 1: Preparing the Node.js Application

### Sample Application Structure

Let's create a production-ready Node.js application structure:

```bash
# Connect to your droplet
ssh deploy@YOUR_DROPLET_IP

# Create application directory
mkdir -p /mnt/app-data/apps/production/nodejs-app
cd /mnt/app-data/apps/production/nodejs-app
```

Create a sample Node.js application:

```javascript
// package.json
{
  "name": "nodejs-production-app",
  "version": "1.0.0",
  "description": "Production Node.js app with Docker and CI/CD",
  "main": "src/server.js",
  "scripts": {
    "start": "node src/server.js",
    "dev": "nodemon src/server.js",
    "test": "jest",
    "lint": "eslint src/",
    "build": "echo 'Build completed'",
    "health-check": "curl -f http://localhost:3000/health || exit 1"
  },
  "dependencies": {
    "express": "^4.18.2",
    "helmet": "^7.0.0",
    "cors": "^2.8.5",
    "morgan": "^1.10.0",
    "dotenv": "^16.3.1",
    "pg": "^8.11.3",
    "redis": "^4.6.7",
    "compression": "^1.7.4"
  },
  "devDependencies": {
    "nodemon": "^3.0.1",
    "jest": "^29.6.2",
    "eslint": "^8.45.0",
    "supertest": "^6.3.3"
  },
  "engines": {
    "node": ">=18.0.0"
  }
}
```

### Create Application Files

```javascript
// src/server.js
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const morgan = require('morgan');
const compression = require('compression');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

// Middleware
app.use(helmet());
app.use(cors());
app.use(compression());
app.use(morgan('combined'));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    version: process.env.APP_VERSION || '1.0.0',
    environment: process.env.NODE_ENV || 'development'
  });
});

// API routes
app.get('/api/status', (req, res) => {
  res.json({
    message: 'API is running',
    environment: process.env.NODE_ENV,
    timestamp: new Date().toISOString()
  });
});

// Default route
app.get('/', (req, res) => {
  res.json({
    message: 'Node.js Production App',
    version: process.env.APP_VERSION || '1.0.0'
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    message: 'Something went wrong!',
    error: process.env.NODE_ENV === 'development' ? err.message : {}
  });
});

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({
    message: 'Route not found'
  });
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received. Shutting down gracefully...');
  server.close(() => {
    console.log('Process terminated');
  });
});

const server = app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Environment: ${process.env.NODE_ENV}`);
});

module.exports = app;
```

### Create Dockerfile

```dockerfile
# Dockerfile
FROM node:18-alpine AS base

# Install security updates
RUN apk update && apk upgrade && apk add --no-cache curl

# Create app directory
WORKDIR /app

# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodeuser -u 1001

# Copy package files
COPY package*.json ./

# Install dependencies
FROM base AS dependencies
RUN npm ci --only=production && npm cache clean --force

# Development stage
FROM base AS development
RUN npm ci
COPY . .
USER nodeuser
EXPOSE 3000
CMD ["npm", "run", "dev"]

# Production stage
FROM base AS production
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .

# Set ownership
RUN chown -R nodeuser:nodejs /app
USER nodeuser

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1

EXPOSE 3000
CMD ["npm", "start"]
```

### Create Docker Compose Configuration

```yaml
# docker-compose.production.yml
version: '3.8'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      target: production
    container_name: nodejs-app
    restart: unless-stopped
    environment:
      - NODE_ENV=production
      - PORT=3000
      - DATABASE_URL=${DATABASE_URL}
      - REDIS_URL=${REDIS_URL}
      - APP_VERSION=${APP_VERSION}
    ports:
      - '3000:3000'
    volumes:
      - /mnt/app-data/docker/volumes/app-logs:/app/logs
    networks:
      - production-network
    depends_on:
      - redis
    healthcheck:
      test: ['CMD', 'curl', '-f', 'http://localhost:3000/health']
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  redis:
    image: redis:7-alpine
    container_name: nodejs-redis
    restart: unless-stopped
    command: redis-server --appendonly yes --requirepass ${REDIS_PASSWORD}
    volumes:
      - /mnt/app-data/docker/volumes/redis-data:/data
    networks:
      - production-network
    healthcheck:
      test: ['CMD', 'redis-cli', '--raw', 'incr', 'ping']
      interval: 30s
      timeout: 3s
      retries: 5

  nginx:
    image: nginx:alpine
    container_name: nodejs-nginx
    restart: unless-stopped
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - /mnt/app-data/docker/volumes/ssl-certs:/etc/ssl/certs:ro
      - /mnt/app-data/docker/volumes/nginx-logs:/var/log/nginx
    networks:
      - production-network
    depends_on:
      - app

networks:
  production-network:
    external: true
```

### Create Nginx Configuration

```nginx
# nginx.conf
events {
    worker_connections 1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    # Logging
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;

    # Basic settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 10M;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    upstream app {
        server app:3000;
    }

    server {
        listen 80;
        server_name _;

        # Health check endpoint for load balancer
        location /health {
            proxy_pass http://app;
            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;
        }

        # Main application
        location / {
            proxy_pass http://app;
            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;

            # Timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;
        }
    }
}
```

## 🔐 Step 2: Setting Up GitHub Repository

### Create Repository Structure

```bash
# In your local development environment
mkdir nodejs-production-app
cd nodejs-production-app

# Initialize git repository
git init
git remote add origin https://github.com/your-username/nodejs-production-app.git

# Create directory structure
mkdir -p .github/workflows
mkdir -p src
mkdir -p tests
mkdir -p scripts
```

### Create Environment Configuration

```bash
# .env.example
NODE_ENV=production
PORT=3000
DATABASE_URL=postgresql://user:password@host:5432/database?sslmode=require
REDIS_URL=redis://:password@localhost:6379
REDIS_PASSWORD=your_redis_password
APP_VERSION=1.0.0
```

### Add Git Configuration

```bash
# .gitignore
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
logs/
*.log
.DS_Store
coverage/
.nyc_output/
.cache/
dist/
```

## ⚙️ Step 3: Creating GitHub Actions Workflow

### Main Deployment Workflow

```yaml
# .github/workflows/deploy.yml
name: Deploy to Digital Ocean

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

env:
  NODE_VERSION: '18'
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: test_db
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run linting
        run: npm run lint

      - name: Run tests
        run: npm test
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_db

  build:
    needs: test
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    outputs:
      image-tag: ${{ steps.meta.outputs.tags }}
      image-digest: ${{ steps.build.outputs.digest }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=sha,prefix={{branch}}-
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push Docker image
        id: build
        uses: docker/build-push-action@v5
        with:
          context: .
          target: production
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

  deploy:
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Deploy to Digital Ocean
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DROPLET_IP }}
          username: ${{ secrets.DROPLET_USER }}
          key: ${{ secrets.DROPLET_SSH_KEY }}
          script: |
            # Set variables
            export IMAGE_TAG="${{ needs.build.outputs.image-tag }}"
            export APP_VERSION="${{ github.sha }}"

            # Navigate to app directory
            cd /mnt/app-data/apps/production/nodejs-app

            # Pull latest code
            git pull origin main

            # Login to GitHub Container Registry
            echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u ${{ github.actor }} --password-stdin

            # Pull new image
            docker pull $IMAGE_TAG

            # Run deployment script
            ./scripts/deploy.sh $IMAGE_TAG
```

### Deployment Script

```bash
# scripts/deploy.sh
#!/bin/bash

set -e

IMAGE_TAG=$1
if [ -z "$IMAGE_TAG" ]; then
    echo "Usage: $0 <image_tag>"
    exit 1
fi

echo "Starting deployment with image: $IMAGE_TAG"

# Load environment variables
if [ -f .env.production ]; then
    export $(cat .env.production | xargs)
fi

# Backup current containers (for rollback)
BACKUP_DIR="/mnt/app-data/backups/deployments/$(date +%Y%m%d_%H%M%S)"
mkdir -p "$BACKUP_DIR"

# Export current container state
docker-compose -f docker-compose.production.yml config > "$BACKUP_DIR/docker-compose-backup.yml"
echo "$IMAGE_TAG" > "$BACKUP_DIR/image-tag.txt"

# Health check function
health_check() {
    local container_name=$1
    local max_attempts=30
    local attempt=1

    echo "Waiting for $container_name to be healthy..."

    while [ $attempt -le $max_attempts ]; do
        if docker exec $container_name curl -f http://localhost:3000/health > /dev/null 2>&1; then
            echo "$container_name is healthy!"
            return 0
        fi

        echo "Attempt $attempt/$max_attempts failed. Retrying in 10 seconds..."
        sleep 10
        attempt=$((attempt + 1))
    done

    echo "$container_name failed health check after $max_attempts attempts"
    return 1
}

# Blue-green deployment simulation
echo "Stopping current containers..."
docker-compose -f docker-compose.production.yml down

echo "Starting new containers with image: $IMAGE_TAG"
export APP_IMAGE=$IMAGE_TAG
docker-compose -f docker-compose.production.yml up -d

# Wait for containers to start
sleep 15

# Health check
if health_check "nodejs-app"; then
    echo "Deployment successful!"

    # Clean up old images (keep last 3)
    docker images --format "table {{.Repository}}:{{.Tag}}\t{{.CreatedAt}}" | grep "ghcr.io/${{ github.repository }}" | tail -n +4 | awk '{print $1}' | xargs -r docker rmi

    # Log successful deployment
    echo "$(date): Successful deployment of $IMAGE_TAG" >> /mnt/app-data/logs/deployments.log
else
    echo "Deployment failed! Rolling back..."

    # Rollback
    docker-compose -f docker-compose.production.yml down
    docker-compose -f "$BACKUP_DIR/docker-compose-backup.yml" up -d

    echo "$(date): Failed deployment of $IMAGE_TAG - rolled back" >> /mnt/app-data/logs/deployments.log
    exit 1
fi
```

## 🔑 Step 4: Setting Up GitHub Secrets

### Required Secrets

Add these secrets to your GitHub repository:

```bash
# Repository Settings > Secrets and variables > Actions

DROPLET_IP=YOUR_DROPLET_IP_ADDRESS
DROPLET_USER=deploy
DROPLET_SSH_KEY=-----BEGIN OPENSSH PRIVATE KEY-----
...your private key content...
-----END OPENSSH PRIVATE KEY-----

# Database credentials
DATABASE_URL=postgresql://myapp_user:password@YOUR_DROPLET_IP:5432/myapp_production?sslmode=require
REDIS_PASSWORD=your_redis_password
```

### Environment Variables on Droplet

```bash
# Create production environment file
cat > /mnt/app-data/apps/production/nodejs-app/.env.production <<EOF
NODE_ENV=production
PORT=3000
DATABASE_URL=postgresql://myapp_user:secure_app_password@localhost:5432/myapp_production?sslmode=require
REDIS_URL=redis://:your_redis_password@nodejs-redis:6379
REDIS_PASSWORD=your_redis_password
APP_VERSION=1.0.0
EOF

# Secure the file
chmod 600 /mnt/app-data/apps/production/nodejs-app/.env.production
```

## 📊 Step 5: Monitoring and Logging Setup

### Application Monitoring Script

```bash
# Create monitoring script
cat > ~/monitor-app.sh <<EOF
#!/bin/bash

APP_NAME="nodejs-app"
LOG_FILE="/mnt/app-data/logs/app-monitor.log"

echo "=== Application Monitor Report - \$(date) ===" >> \$LOG_FILE

# Check container status
echo "Container Status:" >> \$LOG_FILE
docker ps --filter "name=\$APP_NAME" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" >> \$LOG_FILE

# Check application health
echo "Health Check:" >> \$LOG_FILE
if curl -f http://localhost/health > /dev/null 2>&1; then
    echo "✅ Application is healthy" >> \$LOG_FILE
else
    echo "❌ Application health check failed" >> \$LOG_FILE

    # Send alert (you can integrate with your preferred notification service)
    echo "ALERT: Application health check failed at \$(date)" >> \$LOG_FILE
fi

# Check resource usage
echo "Resource Usage:" >> \$LOG_FILE
docker stats --no-stream --format "{{.Container}}: CPU {{.CPUPerc}}, Memory {{.MemUsage}}" \$APP_NAME >> \$LOG_FILE

# Check logs for errors
echo "Recent Errors:" >> \$LOG_FILE
docker logs \$APP_NAME --since 5m 2>&1 | grep -i error | tail -5 >> \$LOG_FILE

echo "================================" >> \$LOG_FILE
echo "" >> \$LOG_FILE
EOF

chmod +x ~/monitor-app.sh

# Add to crontab for monitoring every 5 minutes
crontab -e
# Add: */5 * * * * /home/deploy/monitor-app.sh
```

### Log Aggregation Setup

```bash
# Create log aggregation script
cat > ~/aggregate-logs.sh <<EOF
#!/bin/bash

LOG_DIR="/mnt/app-data/logs"
AGGREGATED_LOG="\$LOG_DIR/aggregated.log"
DATE=\$(date +"%Y-%m-%d %H:%M:%S")

# Collect logs from various sources
echo "[\$DATE] === Log Aggregation Started ===" >> \$AGGREGATED_LOG

# Application logs
echo "[\$DATE] Application Logs:" >> \$AGGREGATED_LOG
docker logs nodejs-app --since 1h --tail 100 >> \$AGGREGATED_LOG 2>&1

# Nginx logs
echo "[\$DATE] Nginx Access Logs:" >> \$AGGREGATED_LOG
tail -50 /mnt/app-data/docker/volumes/nginx-logs/access.log >> \$AGGREGATED_LOG

echo "[\$DATE] Nginx Error Logs:" >> \$AGGREGATED_LOG
tail -20 /mnt/app-data/docker/volumes/nginx-logs/error.log >> \$AGGREGATED_LOG

# System logs
echo "[\$DATE] System Logs:" >> \$AGGREGATED_LOG
journalctl --since "1 hour ago" --no-pager | tail -20 >> \$AGGREGATED_LOG

echo "[\$DATE] === Log Aggregation Completed ===" >> \$AGGREGATED_LOG
echo "" >> \$AGGREGATED_LOG

# Rotate aggregated log if it gets too large (>100MB)
if [ \$(stat -f%z "\$AGGREGATED_LOG" 2>/dev/null || stat -c%s "\$AGGREGATED_LOG") -gt 104857600 ]; then
    mv "\$AGGREGATED_LOG" "\$AGGREGATED_LOG.old"
    echo "[\$(date +"%Y-%m-%d %H:%M:%S")] Log rotated" > "\$AGGREGATED_LOG"
fi
EOF

chmod +x ~/aggregate-logs.sh

# Run hourly
crontab -e
# Add: 0 * * * * /home/deploy/aggregate-logs.sh
```

## 🚀 Step 6: Zero-Downtime Deployment Strategy

### Advanced Deployment Script with Rolling Updates

```bash
# scripts/rolling-deploy.sh
#!/bin/bash

set -e

IMAGE_TAG=$1
BLUE_GREEN=${2:-false}

if [ -z "$IMAGE_TAG" ]; then
    echo "Usage: $0 <image_tag> [blue_green]"
    exit 1
fi

echo "Starting rolling deployment with image: $IMAGE_TAG"

# Configuration
COMPOSE_FILE="docker-compose.production.yml"
APP_SERVICE="app"
BACKUP_DIR="/mnt/app-data/backups/deployments/$(date +%Y%m%d_%H%M%S)"

# Create backup
mkdir -p "$BACKUP_DIR"
docker-compose -f $COMPOSE_FILE config > "$BACKUP_DIR/docker-compose-backup.yml"

# Health check function
health_check() {
    local container_name=$1
    local port=${2:-3000}
    local endpoint=${3:-/health}
    local max_attempts=30
    local attempt=1

    while [ $attempt -le $max_attempts ]; do
        if curl -f "http://localhost:$port$endpoint" > /dev/null 2>&1; then
            echo "$container_name is healthy!"
            return 0
        fi
        sleep 5
        attempt=$((attempt + 1))
    done

    echo "$container_name failed health check"
    return 1
}

if [ "$BLUE_GREEN" = "true" ]; then
    # Blue-Green Deployment
    echo "Performing Blue-Green deployment..."

    # Start new version alongside old
    export APP_IMAGE=$IMAGE_TAG
    export COMPOSE_PROJECT_NAME="green"
    docker-compose -f $COMPOSE_FILE -p green up -d $APP_SERVICE

    # Health check new version
    if health_check "green_${APP_SERVICE}_1" 3001; then
        # Switch traffic (update nginx config)
        echo "Switching traffic to new version..."
        # Update nginx upstream to point to new container
        # This would require a more sophisticated nginx config

        # Stop old version
        docker-compose -f $COMPOSE_FILE -p blue down

        echo "Blue-Green deployment completed successfully"
    else
        echo "New version failed health check, keeping old version"
        docker-compose -f $COMPOSE_FILE -p green down
        exit 1
    fi
else
    # Rolling Update
    echo "Performing rolling update..."

    # Scale up
    export APP_IMAGE=$IMAGE_TAG
    docker-compose -f $COMPOSE_FILE up -d --scale $APP_SERVICE=2 $APP_SERVICE

    # Wait for new container to be healthy
    sleep 10

    # Health check
    NEW_CONTAINER=$(docker-compose -f $COMPOSE_FILE ps -q $APP_SERVICE | head -1)
    if health_check $NEW_CONTAINER; then
        # Scale down to 1 (removes old container)
        docker-compose -f $COMPOSE_FILE up -d --scale $APP_SERVICE=1 $APP_SERVICE
        echo "Rolling update completed successfully"
    else
        echo "New container failed health check, rolling back"
        docker-compose -f $COMPOSE_FILE up -d --scale $APP_SERVICE=1 $APP_SERVICE
        exit 1
    fi
fi

# Cleanup old images
docker image prune -f

echo "Deployment completed at $(date)"
```

## 📈 Step 7: Performance Monitoring

### Application Performance Monitoring

```javascript
// src/middleware/monitoring.js
const performanceMonitoring = (req, res, next) => {
  const start = Date.now();

  res.on('finish', () => {
    const duration = Date.now() - start;
    const logData = {
      method: req.method,
      url: req.url,
      status: res.statusCode,
      duration: `${duration}ms`,
      timestamp: new Date().toISOString(),
      userAgent: req.get('User-Agent'),
      ip: req.ip
    };

    // Log performance data
    console.log('PERFORMANCE:', JSON.stringify(logData));

    // Alert on slow requests
    if (duration > 5000) {
      console.warn('SLOW_REQUEST:', JSON.stringify(logData));
    }
  });

  next();
};

module.exports = { performanceMonitoring };
```

### System Resource Monitoring

```bash
# Create resource monitoring script
cat > ~/resource-monitor.sh <<EOF
#!/bin/bash

ALERT_THRESHOLD_CPU=80
ALERT_THRESHOLD_MEM=80
LOG_FILE="/mnt/app-data/logs/resource-monitor.log"

# Get system resources
CPU_USAGE=\$(top -bn1 | grep "Cpu(s)" | awk '{print \$2}' | awk -F'%' '{print \$1}')
MEM_USAGE=\$(free | grep Mem | awk '{printf("%.1f"), \$3/\$2 * 100.0}')
DISK_USAGE=\$(df -h /mnt/app-data | tail -1 | awk '{print \$5}' | sed 's/%//')

# Log current usage
echo "\$(date): CPU: \${CPU_USAGE}%, Memory: \${MEM_USAGE}%, Disk: \${DISK_USAGE}%" >> \$LOG_FILE

# Check thresholds and alert
if (( \$(echo "\$CPU_USAGE > \$ALERT_THRESHOLD_CPU" | bc -l) )); then
    echo "ALERT: High CPU usage: \${CPU_USAGE}%" >> \$LOG_FILE
fi

if (( \$(echo "\$MEM_USAGE > \$ALERT_THRESHOLD_MEM" | bc -l) )); then
    echo "ALERT: High Memory usage: \${MEM_USAGE}%" >> \$LOG_FILE
fi

if [ "\$DISK_USAGE" -gt 85 ]; then
    echo "ALERT: High Disk usage: \${DISK_USAGE}%" >> \$LOG_FILE
fi

# Docker container resources
echo "Container Resources:" >> \$LOG_FILE
docker stats --no-stream --format "{{.Container}}: CPU {{.CPUPerc}}, Memory {{.MemUsage}}" >> \$LOG_FILE
echo "---" >> \$LOG_FILE
EOF

chmod +x ~/resource-monitor.sh

# Run every 10 minutes
crontab -e
# Add: */10 * * * * /home/deploy/resource-monitor.sh
```

## ✅ Step 8: Testing the Complete Pipeline

### Test Deployment Pipeline

```bash
# Create comprehensive test script
cat > ~/test-deployment.sh <<EOF
#!/bin/bash

echo "=== Testing Complete Deployment Pipeline ==="

# Test 1: Application health
echo "1. Testing application health..."
curl -f http://localhost/health
echo "✅ Health check passed"

# Test 2: API endpoints
echo "2. Testing API endpoints..."
curl -f http://localhost/api/status
echo "✅ API endpoints working"

# Test 3: Container status
echo "3. Checking container status..."
docker ps --filter "name=nodejs" --format "table {{.Names}}\t{{.Status}}"

# Test 4: Log collection
echo "4. Testing log collection..."
docker logs nodejs-app --tail 10

# Test 5: Resource usage
echo "5. Checking resource usage..."
docker stats --no-stream nodejs-app

# Test 6: Database connectivity (if applicable)
echo "6. Testing database connectivity..."
docker exec nodejs-app node -e "
const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });
client.connect().then(() => {
    console.log('✅ Database connection successful');
    client.end();
}).catch(err => {
    console.log('❌ Database connection failed:', err.message);
});
"

echo "=== All Tests Completed ==="
EOF

chmod +x ~/test-deployment.sh
./test-deployment.sh
```

## 🎉 What You've Accomplished

Congratulations! You now have a complete CI/CD pipeline with:

✅ **Automated Testing**: GitHub Actions runs tests on every push  
✅ **Containerized Deployment**: Docker-based application deployment  
✅ **Zero-Downtime Deployments**: Rolling updates with health checks  
✅ **Monitoring & Alerting**: Application and resource monitoring  
✅ **Rollback Strategy**: Automatic rollback on deployment failures  
✅ **Security**: Secure secrets management and container security  
✅ **Performance Monitoring**: Application performance tracking  
✅ **Log Aggregation**: Centralized logging with rotation

### Deployment Flow Summary

1. **Push to main branch** → Triggers GitHub Actions
2. **Run tests** → Linting, unit tests, integration tests
3. **Build Docker image** → Push to GitHub Container Registry
4. **Deploy to server** → SSH to droplet, pull image, deploy
5. **Health checks** → Verify application is running correctly
6. **Monitor** → Continuous monitoring and alerting

## 🔗 Quick Reference Commands

```bash
# Manual deployment
cd /mnt/app-data/apps/production/nodejs-app
./scripts/deploy.sh ghcr.io/username/repo:latest

# Check application status
curl http://localhost/health
docker ps --filter "name=nodejs"

# View logs
docker logs nodejs-app -f
tail -f /mnt/app-data/logs/app-monitor.log

# Resource monitoring
./resource-monitor.sh
./monitor-app.sh

# Emergency rollback
docker-compose -f docker-compose.production.yml down
# Restore from backup in /mnt/app-data/backups/deployments/
```

## 🔮 Coming Up in Part 5

In the next part of our series, we'll:

- Set up multiple environments (staging, development)
- Deploy different branches to different environments
- Configure environment-specific variables and resources
- Implement branch-based deployment strategies
- Set up environment promotion workflows

---

_Ready to manage multiple environments? Let's set up staging and development environments!_

**Next**: [Digital Ocean Mastery Part 5: Multi-Environment Deployments](/blog/digital-ocean-part-5-multi-environment-deployments)

---

## Digital Ocean Mastery Part 5: Multi-Environment Deployments

Set up staging, production, and development environments on Digital Ocean. Deploy different branches to separate environments with automated workflows.

- Canonical page: https://joshua-ansah.vercel.app/blog/digital-ocean-part-5-multi-environment-deployments
- Author: Joshua Ansah
- Published: September 14, 2025
- Category: DevOps
- Topics: Multi-Environment, Staging, Production, Branches, Digital Ocean

Welcome to Part 5 of our Digital Ocean mastery series! Building on our automated deployment pipeline, we'll now create multiple environments (development, staging, and production) with branch-based deployment strategies. This setup enables safe testing and gradual rollouts.

## 🎯 What You'll Learn

In this comprehensive guide, we'll cover:

- Setting up multiple environments on a single droplet
- Branch-based deployment strategies
- Environment-specific configurations and resources
- Database isolation between environments
- Network segmentation for security
- Environment promotion workflows
- Resource management and optimization
- Monitoring across multiple environments

## 📋 Prerequisites

Before starting, ensure you have:

- Completed [Parts 1-4](/blog/digital-ocean-part-1-droplet-storage-setup) of this series
- Understanding of Git branching strategies
- Basic knowledge of environment management
- Access to your GitHub repository with proper branch structure

## 🏗️ Step 1: Environment Architecture Setup

### Create Environment Directory Structure

```bash
# Connect to your droplet
ssh deploy@YOUR_DROPLET_IP

# Create environment-specific directories
mkdir -p /mnt/app-data/environments/{production,staging,development}

# Create shared resources directory
mkdir -p /mnt/app-data/shared/{databases,logs,backups,configs}

# Set up environment-specific subdirectories
for env in production staging development; do
    mkdir -p /mnt/app-data/environments/$env/{app,configs,logs,data}
done

# Create symlinks for easy access
ln -s /mnt/app-data/environments ~/environments
```

### Environment Resource Allocation

```bash
# Create resource allocation script
cat > ~/setup-environments.sh <<EOF
#!/bin/bash

# Environment resource allocation
TOTAL_MEMORY=2048  # 2GB droplet
PRODUCTION_MEMORY=1024
STAGING_MEMORY=512
DEVELOPMENT_MEMORY=256

echo "Setting up environment resource allocation..."

# Create environment-specific Docker Compose overrides
for env in production staging development; do
    case $env in
        production)
            memory_limit="${PRODUCTION_MEMORY}m"
            cpu_limit="0.7"
            replicas=1
            ;;
        staging)
            memory_limit="${STAGING_MEMORY}m"
            cpu_limit="0.2"
            replicas=1
            ;;
        development)
            memory_limit="${DEVELOPMENT_MEMORY}m"
            cpu_limit="0.1"
            replicas=1
            ;;
    esac

    cat > /mnt/app-data/environments/$env/docker-compose.override.yml <<EOL
version: '3.8'

services:
  app:
    deploy:
      resources:
        limits:
          memory: $memory_limit
          cpus: '$cpu_limit'
        reservations:
          memory: $(($memory_limit/2))m
          cpus: '0.1'
      replicas: $replicas

  redis:
    deploy:
      resources:
        limits:
          memory: 128m
          cpus: '0.1'
        reservations:
          memory: 64m
          cpus: '0.05'
EOL

done

echo "Environment resource allocation completed!"
EOF

chmod +x ~/setup-environments.sh
./setup-environments.sh
```

## 🌐 Step 2: Network Segmentation

### Create Environment-Specific Networks

```bash
# Create isolated networks for each environment
docker network create --driver bridge \
    --subnet=172.20.0.0/24 \
    --gateway=172.20.0.1 \
    production-network

docker network create --driver bridge \
    --subnet=172.21.0.0/24 \
    --gateway=172.21.0.1 \
    staging-network

docker network create --driver bridge \
    --subnet=172.22.0.0/24 \
    --gateway=172.22.0.1 \
    development-network

# Create a shared database network
docker network create --driver bridge \
    --subnet=172.23.0.0/24 \
    --gateway=172.23.0.1 \
    database-network

# List all networks
docker network ls
```

### Configure Port Allocation

```bash
# Create port allocation configuration
cat > ~/environments/port-allocation.conf <<EOF
# Port Allocation for Environments
# Format: ENVIRONMENT:SERVICE:HOST_PORT:CONTAINER_PORT

# Production Environment (80xx range)
production:app:8000:3000
production:nginx:80:80
production:nginx-ssl:443:443
production:redis:6380:6379

# Staging Environment (81xx range)
staging:app:8100:3000
staging:nginx:8101:80
staging:redis:6381:6379

# Development Environment (82xx range)
development:app:8200:3000
development:nginx:8201:80
development:redis:6382:6379

# Monitoring (90xx range)
monitoring:portainer:9000:9000
monitoring:grafana:9001:3000
monitoring:prometheus:9002:9090
EOF
```

## 🗄️ Step 3: Database Environment Isolation

### Create Environment-Specific Databases

```bash
# Connect to PostgreSQL and create environment databases
sudo -i -u postgres psql
```

```sql
-- Create environment-specific databases
CREATE DATABASE myapp_production;
CREATE DATABASE myapp_staging;
CREATE DATABASE myapp_development;

-- Create environment-specific users
CREATE USER myapp_prod WITH PASSWORD 'prod_secure_password';
CREATE USER myapp_staging WITH PASSWORD 'staging_secure_password';
CREATE USER myapp_dev WITH PASSWORD 'dev_secure_password';

-- Grant privileges to respective databases
GRANT ALL PRIVILEGES ON DATABASE myapp_production TO myapp_prod;
GRANT ALL PRIVILEGES ON DATABASE myapp_staging TO myapp_staging;
GRANT ALL PRIVILEGES ON DATABASE myapp_development TO myapp_dev;

-- Configure connection limits per environment
ALTER USER myapp_prod CONNECTION LIMIT 20;
ALTER USER myapp_staging CONNECTION LIMIT 10;
ALTER USER myapp_dev CONNECTION LIMIT 5;

-- Exit PostgreSQL
\q
```

```bash
# Exit postgres user
exit
```

### Environment Database Configuration

```bash
# Create database initialization scripts for each environment
for env in production staging development; do
    cat > ~/environments/$env/init-db.sql <<EOF
-- Database initialization for $env environment
CREATE SCHEMA IF NOT EXISTS app_schema;
SET search_path TO app_schema, public;

-- Example tables (adjust based on your application)
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS logs (
    id SERIAL PRIMARY KEY,
    level VARCHAR(50) NOT NULL,
    message TEXT NOT NULL,
    metadata JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Environment-specific configurations
INSERT INTO app_configuration (key, value) VALUES
    ('environment', '$env'),
    ('debug_mode', $([ "$env" = "development" ] && echo "true" || echo "false")),
    ('log_level', $([ "$env" = "production" ] && echo "'error'" || echo "'debug'"))
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
EOF
done
```

## 📝 Step 4: Environment-Specific Configurations

### Create Environment Configuration Files

```bash
# Production environment configuration
cat > ~/environments/production/.env <<EOF
# Production Environment Configuration
NODE_ENV=production
PORT=3000
DEBUG=false

# Database
DATABASE_URL=postgresql://myapp_prod:prod_secure_password@localhost:5432/myapp_production?sslmode=require

# Redis
REDIS_URL=redis://:prod_redis_password@localhost:6380
REDIS_PASSWORD=prod_redis_password

# Application
APP_NAME=MyApp Production
APP_VERSION=1.0.0
LOG_LEVEL=error
MAX_REQUEST_SIZE=10mb

# Security
SESSION_SECRET=production_session_secret_very_long_and_secure
JWT_SECRET=production_jwt_secret_very_long_and_secure
CORS_ORIGIN=https://yourdomain.com

# External Services
API_BASE_URL=https://api.yourdomain.com
STATIC_FILES_URL=https://cdn.yourdomain.com
EOF

# Staging environment configuration
cat > ~/environments/staging/.env <<EOF
# Staging Environment Configuration
NODE_ENV=staging
PORT=3000
DEBUG=true

# Database
DATABASE_URL=postgresql://myapp_staging:staging_secure_password@localhost:5432/myapp_staging?sslmode=require

# Redis
REDIS_URL=redis://:staging_redis_password@localhost:6381
REDIS_PASSWORD=staging_redis_password

# Application
APP_NAME=MyApp Staging
APP_VERSION=staging
LOG_LEVEL=debug
MAX_REQUEST_SIZE=10mb

# Security
SESSION_SECRET=staging_session_secret_change_in_production
JWT_SECRET=staging_jwt_secret_change_in_production
CORS_ORIGIN=https://staging.yourdomain.com

# External Services
API_BASE_URL=https://staging-api.yourdomain.com
STATIC_FILES_URL=https://staging-cdn.yourdomain.com
EOF

# Development environment configuration
cat > ~/environments/development/.env <<EOF
# Development Environment Configuration
NODE_ENV=development
PORT=3000
DEBUG=true

# Database
DATABASE_URL=postgresql://myapp_dev:dev_secure_password@localhost:5432/myapp_development?sslmode=require

# Redis
REDIS_URL=redis://:dev_redis_password@localhost:6382
REDIS_PASSWORD=dev_redis_password

# Application
APP_NAME=MyApp Development
APP_VERSION=dev
LOG_LEVEL=debug
MAX_REQUEST_SIZE=50mb

# Security
SESSION_SECRET=dev_session_secret_not_for_production
JWT_SECRET=dev_jwt_secret_not_for_production
CORS_ORIGIN=*

# External Services
API_BASE_URL=http://localhost:8200
STATIC_FILES_URL=http://localhost:8200/static
EOF

# Secure environment files
chmod 600 ~/environments/*/.env
```

### Create Environment-Specific Docker Compose Files

```bash
# Production Docker Compose
cat > ~/environments/production/docker-compose.yml <<EOF
version: '3.8'

services:
  app:
    image: \${APP_IMAGE:-ghcr.io/your-username/your-repo:latest}
    container_name: production-app
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "8000:3000"
    volumes:
      - /mnt/app-data/environments/production/logs:/app/logs
      - /mnt/app-data/shared/configs:/app/configs:ro
    networks:
      - production-network
      - database-network
    depends_on:
      - redis
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  redis:
    image: redis:7-alpine
    container_name: production-redis
    restart: unless-stopped
    command: redis-server --appendonly yes --requirepass \${REDIS_PASSWORD}
    ports:
      - "6380:6379"
    volumes:
      - /mnt/app-data/environments/production/data/redis:/data
    networks:
      - production-network

  nginx:
    image: nginx:alpine
    container_name: production-nginx
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - /mnt/app-data/shared/ssl-certs:/etc/ssl/certs:ro
      - /mnt/app-data/environments/production/logs/nginx:/var/log/nginx
    networks:
      - production-network
    depends_on:
      - app

networks:
  production-network:
    external: true
  database-network:
    external: true
EOF

# Staging Docker Compose
cat > ~/environments/staging/docker-compose.yml <<EOF
version: '3.8'

services:
  app:
    image: \${APP_IMAGE:-ghcr.io/your-username/your-repo:staging}
    container_name: staging-app
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "8100:3000"
    volumes:
      - /mnt/app-data/environments/staging/logs:/app/logs
      - /mnt/app-data/shared/configs:/app/configs:ro
    networks:
      - staging-network
      - database-network
    depends_on:
      - redis
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  redis:
    image: redis:7-alpine
    container_name: staging-redis
    restart: unless-stopped
    command: redis-server --appendonly yes --requirepass \${REDIS_PASSWORD}
    ports:
      - "6381:6379"
    volumes:
      - /mnt/app-data/environments/staging/data/redis:/data
    networks:
      - staging-network

  nginx:
    image: nginx:alpine
    container_name: staging-nginx
    restart: unless-stopped
    ports:
      - "8101:80"
    volumes:
      - ./nginx-staging.conf:/etc/nginx/nginx.conf:ro
      - /mnt/app-data/environments/staging/logs/nginx:/var/log/nginx
    networks:
      - staging-network
    depends_on:
      - app

networks:
  staging-network:
    external: true
  database-network:
    external: true
EOF

# Development Docker Compose
cat > ~/environments/development/docker-compose.yml <<EOF
version: '3.8'

services:
  app:
    image: \${APP_IMAGE:-ghcr.io/your-username/your-repo:dev}
    container_name: development-app
    restart: unless-stopped
    env_file:
      - .env
    ports:
      - "8200:3000"
    volumes:
      - /mnt/app-data/environments/development/logs:/app/logs
      - /mnt/app-data/shared/configs:/app/configs:ro
    networks:
      - development-network
      - database-network
    depends_on:
      - redis
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 60s
      timeout: 10s
      retries: 2
      start_period: 30s

  redis:
    image: redis:7-alpine
    container_name: development-redis
    restart: unless-stopped
    command: redis-server --appendonly yes --requirepass \${REDIS_PASSWORD}
    ports:
      - "6382:6379"
    volumes:
      - /mnt/app-data/environments/development/data/redis:/data
    networks:
      - development-network

networks:
  development-network:
    external: true
  database-network:
    external: true
EOF
```

## 🚀 Step 5: Branch-Based Deployment Strategy

### Update GitHub Actions Workflow

```yaml
# .github/workflows/multi-environment-deploy.yml
name: Multi-Environment Deploy

on:
  push:
    branches: [main, staging, develop]
  pull_request:
    branches: [main, staging]

env:
  NODE_VERSION: '18'
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  test:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [18, 20]

    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: test_db
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run linting
        run: npm run lint

      - name: Run tests
        run: npm test
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_db

  build:
    needs: test
    runs-on: ubuntu-latest
    if: github.event_name == 'push'

    outputs:
      image-tag: ${{ steps.meta.outputs.tags }}
      environment: ${{ steps.env.outputs.environment }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Determine environment
        id: env
        run: |
          if [[ ${{ github.ref }} == 'refs/heads/main' ]]; then
            echo "environment=production" >> $GITHUB_OUTPUT
            echo "image-suffix=" >> $GITHUB_OUTPUT
          elif [[ ${{ github.ref }} == 'refs/heads/staging' ]]; then
            echo "environment=staging" >> $GITHUB_OUTPUT
            echo "image-suffix=-staging" >> $GITHUB_OUTPUT
          elif [[ ${{ github.ref }} == 'refs/heads/develop' ]]; then
            echo "environment=development" >> $GITHUB_OUTPUT
            echo "image-suffix=-dev" >> $GITHUB_OUTPUT
          fi

      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch,suffix=${{ steps.env.outputs.image-suffix }}
            type=sha,prefix=${{ steps.env.outputs.environment }}-
            type=raw,value=${{ steps.env.outputs.environment }}-latest

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          target: production
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

  deploy-development:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/develop'
    environment: development

    steps:
      - name: Deploy to Development
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DROPLET_IP }}
          username: ${{ secrets.DROPLET_USER }}
          key: ${{ secrets.DROPLET_SSH_KEY }}
          script: |
            cd ~/environments/development
            export APP_IMAGE="${{ needs.build.outputs.image-tag }}"
            ./deploy.sh development

  deploy-staging:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/staging'
    environment: staging

    steps:
      - name: Deploy to Staging
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DROPLET_IP }}
          username: ${{ secrets.DROPLET_USER }}
          key: ${{ secrets.DROPLET_SSH_KEY }}
          script: |
            cd ~/environments/staging
            export APP_IMAGE="${{ needs.build.outputs.image-tag }}"
            ./deploy.sh staging

  deploy-production:
    needs: build
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    environment: production

    steps:
      - name: Deploy to Production
        uses: appleboy/ssh-action@v1.0.0
        with:
          host: ${{ secrets.DROPLET_IP }}
          username: ${{ secrets.DROPLET_USER }}
          key: ${{ secrets.DROPLET_SSH_KEY }}
          script: |
            cd ~/environments/production
            export APP_IMAGE="${{ needs.build.outputs.image-tag }}"
            ./deploy.sh production

  promote-to-staging:
    needs: deploy-development
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/develop' && github.event_name == 'push'
    environment: promote-to-staging

    steps:
      - name: Create promotion PR
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.pulls.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: 'Auto: Promote develop to staging',
              head: 'develop',
              base: 'staging',
              body: 'Automated promotion from development to staging environment.'
            });
```

### Create Environment-Specific Deployment Scripts

```bash
# Create deployment script for each environment
for env in production staging development; do
    cat > ~/environments/$env/deploy.sh <<EOF
#!/bin/bash

set -e

ENVIRONMENT=$1
IMAGE_TAG=\${APP_IMAGE:-\$2}

if [ -z "\$ENVIRONMENT" ] || [ -z "\$IMAGE_TAG" ]; then
    echo "Usage: \$0 <environment> [image_tag]"
    echo "Environment: production, staging, development"
    exit 1
fi

echo "Deploying \$IMAGE_TAG to \$ENVIRONMENT environment..."

# Configuration
COMPOSE_FILE="docker-compose.yml"
BACKUP_DIR="/mnt/app-data/backups/deployments/\$ENVIRONMENT/\$(date +%Y%m%d_%H%M%S)"

# Create backup
mkdir -p "\$BACKUP_DIR"
docker-compose -f \$COMPOSE_FILE config > "\$BACKUP_DIR/docker-compose-backup.yml"
echo "\$IMAGE_TAG" > "\$BACKUP_DIR/image-tag.txt"

# Health check function
health_check() {
    local container_name=\$1
    local port=\$2
    local max_attempts=30
    local attempt=1

    while [ \$attempt -le \$max_attempts ]; do
        if curl -f "http://localhost:\$port/health" > /dev/null 2>&1; then
            echo "\$container_name is healthy!"
            return 0
        fi
        sleep 10
        attempt=\$((attempt + 1))
    done

    echo "\$container_name failed health check"
    return 1
}

# Get port based on environment
case \$ENVIRONMENT in
    production) PORT=8000 ;;
    staging) PORT=8100 ;;
    development) PORT=8200 ;;
    *) echo "Unknown environment: \$ENVIRONMENT"; exit 1 ;;
esac

# Stop current containers
echo "Stopping current containers..."
docker-compose -f \$COMPOSE_FILE down

# Pull new image
echo "Pulling new image: \$IMAGE_TAG"
docker pull "\$IMAGE_TAG"

# Start new containers
echo "Starting new containers..."
export APP_IMAGE="\$IMAGE_TAG"
docker-compose -f \$COMPOSE_FILE up -d

# Wait for containers to initialize
sleep 20

# Health check
if health_check "\$ENVIRONMENT-app" \$PORT; then
    echo "Deployment to \$ENVIRONMENT successful!"

    # Log successful deployment
    echo "\$(date): Successful deployment of \$IMAGE_TAG to \$ENVIRONMENT" >> /mnt/app-data/logs/deployments-\$ENVIRONMENT.log

    # Clean up old images (keep last 3)
    docker images --format "table {{.Repository}}:{{.Tag}}\t{{.CreatedAt}}" | grep "\$IMAGE_TAG" | tail -n +4 | awk '{print \$1}' | xargs -r docker rmi || true
else
    echo "Deployment to \$ENVIRONMENT failed! Rolling back..."

    # Rollback
    docker-compose -f \$COMPOSE_FILE down
    if [ -f "\$BACKUP_DIR/docker-compose-backup.yml" ]; then
        OLD_IMAGE=\$(cat "\$BACKUP_DIR/image-tag.txt" 2>/dev/null || echo "")
        if [ -n "\$OLD_IMAGE" ]; then
            export APP_IMAGE="\$OLD_IMAGE"
            docker-compose -f \$COMPOSE_FILE up -d
        fi
    fi

    echo "\$(date): Failed deployment of \$IMAGE_TAG to \$ENVIRONMENT - rolled back" >> /mnt/app-data/logs/deployments-\$ENVIRONMENT.log
    exit 1
fi
EOF

    chmod +x ~/environments/$env/deploy.sh
done
```

## 🔄 Step 6: Environment Promotion Workflow

### Create Promotion Scripts

```bash
# Create environment promotion script
cat > ~/promote-environment.sh <<EOF
#!/bin/bash

set -e

SOURCE_ENV=\$1
TARGET_ENV=\$2

if [ -z "\$SOURCE_ENV" ] || [ -z "\$TARGET_ENV" ]; then
    echo "Usage: \$0 <source_environment> <target_environment>"
    echo "Environments: development, staging, production"
    exit 1
fi

echo "Promoting from \$SOURCE_ENV to \$TARGET_ENV..."

# Validate environments
for env in "\$SOURCE_ENV" "\$TARGET_ENV"; do
    if [ ! -d "~/environments/\$env" ]; then
        echo "Environment directory not found: \$env"
        exit 1
    fi
done

# Get current image from source environment
cd ~/environments/\$SOURCE_ENV
SOURCE_IMAGE=\$(docker-compose ps -q app | xargs docker inspect --format='{{.Config.Image}}')

if [ -z "\$SOURCE_IMAGE" ]; then
    echo "Could not determine source image from \$SOURCE_ENV"
    exit 1
fi

echo "Promoting image: \$SOURCE_IMAGE"

# Health check source environment
if ! curl -f "http://localhost:\$(cat port.txt 2>/dev/null || echo 8000)/health" > /dev/null 2>&1; then
    echo "Source environment \$SOURCE_ENV is not healthy. Aborting promotion."
    exit 1
fi

# Deploy to target environment
cd ~/environments/\$TARGET_ENV
export APP_IMAGE="\$SOURCE_IMAGE"
./deploy.sh \$TARGET_ENV "\$SOURCE_IMAGE"

echo "Promotion from \$SOURCE_ENV to \$TARGET_ENV completed!"

# Log promotion
echo "\$(date): Promoted \$SOURCE_IMAGE from \$SOURCE_ENV to \$TARGET_ENV" >> /mnt/app-data/logs/promotions.log
EOF

chmod +x ~/promote-environment.sh
```

### Database Migration Workflow

```bash
# Create database migration script
cat > ~/migrate-database.sh <<EOF
#!/bin/bash

set -e

ENVIRONMENT=\$1
MIGRATION_DIRECTION=\${2:-up}

if [ -z "\$ENVIRONMENT" ]; then
    echo "Usage: \$0 <environment> [up|down]"
    exit 1
fi

echo "Running database migrations for \$ENVIRONMENT environment..."

# Load environment configuration
cd ~/environments/\$ENVIRONMENT
source .env

# Run migrations (adjust based on your migration tool)
case \$ENVIRONMENT in
    production)
        echo "Running production migrations with extra caution..."
        # Backup database before migration
        pg_dump "\$DATABASE_URL" > "/mnt/app-data/backups/db-before-migration-\$(date +%Y%m%d_%H%M%S).sql"
        ;;
    staging)
        echo "Running staging migrations..."
        ;;
    development)
        echo "Running development migrations..."
        ;;
esac

# Run migrations using your application's migration command
# Example for Node.js with a migration framework:
docker exec \$ENVIRONMENT-app npm run migrate:\$MIGRATION_DIRECTION

echo "Database migrations completed for \$ENVIRONMENT"
EOF

chmod +x ~/migrate-database.sh
```

## 📊 Step 7: Multi-Environment Monitoring

### Create Environment Monitoring Dashboard

```bash
# Create comprehensive monitoring script
cat > ~/monitor-environments.sh <<EOF
#!/bin/bash

LOG_FILE="/mnt/app-data/logs/environment-monitor.log"

echo "=== Multi-Environment Monitor Report - \$(date) ===" >> \$LOG_FILE

for env in production staging development; do
    echo "--- \$env Environment ---" >> \$LOG_FILE

    # Check container status
    cd ~/environments/\$env

    # Get expected port
    case \$env in
        production) PORT=8000 ;;
        staging) PORT=8100 ;;
        development) PORT=8200 ;;
    esac

    # Container health
    if docker-compose ps | grep -q "Up"; then
        echo "✅ Containers: Running" >> \$LOG_FILE
    else
        echo "❌ Containers: Stopped or Failed" >> \$LOG_FILE
    fi

    # Application health
    if curl -f "http://localhost:\$PORT/health" > /dev/null 2>&1; then
        echo "✅ Application: Healthy" >> \$LOG_FILE
    else
        echo "❌ Application: Unhealthy" >> \$LOG_FILE
    fi

    # Resource usage
    APP_CONTAINER="\$env-app"
    if docker ps --format '{{.Names}}' | grep -q "\$APP_CONTAINER"; then
        STATS=\$(docker stats --no-stream --format "{{.CPUPerc}}\t{{.MemUsage}}" \$APP_CONTAINER)
        echo "📊 Resources: \$STATS" >> \$LOG_FILE
    else
        echo "📊 Resources: Container not running" >> \$LOG_FILE
    fi

    echo "" >> \$LOG_FILE
done

echo "================================" >> \$LOG_FILE
echo "" >> \$LOG_FILE
EOF

chmod +x ~/monitor-environments.sh

# Add to crontab for regular monitoring
crontab -e
# Add: */15 * * * * /home/deploy/monitor-environments.sh
```

### Create Environment Health Check API

```bash
# Create a simple health check aggregator
cat > ~/health-check-api.py <<EOF
#!/usr/bin/env python3

import json
import subprocess
import sys
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler

class HealthCheckHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/health/all':
            health_data = self.check_all_environments()
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(json.dumps(health_data, indent=2).encode())
        else:
            self.send_response(404)
            self.end_headers()

    def check_all_environments(self):
        environments = ['production', 'staging', 'development']
        ports = {'production': 8000, 'staging': 8100, 'development': 8200}

        health_data = {
            'timestamp': datetime.now().isoformat(),
            'environments': {}
        }

        for env in environments:
            try:
                # Check if container is running
                container_check = subprocess.run(
                    ['docker', 'ps', '--filter', f'name={env}-app', '--format', '{{.Status}}'],
                    capture_output=True, text=True
                )

                # Check application health endpoint
                health_check = subprocess.run(
                    ['curl', '-f', f'http://localhost:{ports[env]}/health'],
                    capture_output=True, text=True, timeout=5
                )

                health_data['environments'][env] = {
                    'container_running': 'Up' in container_check.stdout,
                    'application_healthy': health_check.returncode == 0,
                    'port': ports[env],
                    'status': 'healthy' if health_check.returncode == 0 else 'unhealthy'
                }
            except Exception as e:
                health_data['environments'][env] = {
                    'container_running': False,
                    'application_healthy': False,
                    'port': ports[env],
                    'status': 'error',
                    'error': str(e)
                }

        return health_data

if __name__ == '__main__':
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 9999
    server = HTTPServer(('0.0.0.0', port), HealthCheckHandler)
    print(f'Health check API running on port {port}')
    server.serve_forever()
EOF

chmod +x ~/health-check-api.py

# Create systemd service for health check API
sudo tee /etc/systemd/system/health-check-api.service > /dev/null <<EOF
[Unit]
Description=Environment Health Check API
After=network.target

[Service]
Type=simple
User=deploy
WorkingDirectory=/home/deploy
ExecStart=/home/deploy/health-check-api.py 9999
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# Enable and start the service
sudo systemctl enable health-check-api
sudo systemctl start health-check-api
```

## 🔄 Step 8: Environment Synchronization

### Create Data Synchronization Scripts

```bash
# Create data sync script (for development/staging)
cat > ~/sync-data.sh <<EOF
#!/bin/bash

set -e

SOURCE_ENV=\$1
TARGET_ENV=\$2
DATA_TYPE=\${3:-all}

if [ -z "\$SOURCE_ENV" ] || [ -z "\$TARGET_ENV" ]; then
    echo "Usage: \$0 <source_env> <target_env> [database|files|all]"
    exit 1
fi

# Safety check - never sync TO production
if [ "\$TARGET_ENV" = "production" ]; then
    echo "ERROR: Cannot sync TO production environment for safety reasons"
    exit 1
fi

echo "Syncing \$DATA_TYPE from \$SOURCE_ENV to \$TARGET_ENV..."

# Load environment configurations
source ~/environments/\$SOURCE_ENV/.env
SOURCE_DB_URL=\$DATABASE_URL

source ~/environments/\$TARGET_ENV/.env
TARGET_DB_URL=\$DATABASE_URL

if [ "\$DATA_TYPE" = "database" ] || [ "\$DATA_TYPE" = "all" ]; then
    echo "Syncing database..."

    # Create temporary dump
    TEMP_DUMP="/tmp/sync-\$(date +%Y%m%d_%H%M%S).sql"

    # Dump source database
    pg_dump "\$SOURCE_DB_URL" > "\$TEMP_DUMP"

    # Restore to target database (with confirmation)
    echo "WARNING: This will replace all data in \$TARGET_ENV database!"
    read -p "Are you sure? (yes/no): " confirm

    if [ "\$confirm" = "yes" ]; then
        # Drop and recreate target database
        TARGET_DB_NAME=\$(echo "\$TARGET_DB_URL" | sed 's/.*\///' | sed 's/\?.*//')
        sudo -u postgres dropdb "\$TARGET_DB_NAME"
        sudo -u postgres createdb "\$TARGET_DB_NAME"

        # Restore data
        psql "\$TARGET_DB_URL" < "\$TEMP_DUMP"

        echo "Database sync completed"
    else
        echo "Database sync cancelled"
    fi

    # Cleanup
    rm "\$TEMP_DUMP"
fi

if [ "\$DATA_TYPE" = "files" ] || [ "\$DATA_TYPE" = "all" ]; then
    echo "Syncing uploaded files..."

    # Sync uploaded files (adjust paths based on your application)
    rsync -av \
        ~/environments/\$SOURCE_ENV/data/ \
        ~/environments/\$TARGET_ENV/data/

    echo "File sync completed"
fi

echo "Synchronization from \$SOURCE_ENV to \$TARGET_ENV completed!"
EOF

chmod +x ~/sync-data.sh
```

## ✅ Step 9: Testing Multi-Environment Setup

### Comprehensive Environment Test

```bash
# Create comprehensive test script
cat > ~/test-environments.sh <<EOF
#!/bin/bash

echo "=== Testing Multi-Environment Setup ==="

# Test 1: Network connectivity
echo "1. Testing network connectivity..."
for env in production staging development; do
    case \$env in
        production) PORT=8000 ;;
        staging) PORT=8100 ;;
        development) PORT=8200 ;;
    esac

    if curl -f "http://localhost:\$PORT/health" > /dev/null 2>&1; then
        echo "✅ \$env environment accessible on port \$PORT"
    else
        echo "❌ \$env environment not accessible on port \$PORT"
    fi
done

# Test 2: Database connectivity
echo "2. Testing database connectivity..."
for env in production staging development; do
    cd ~/environments/\$env
    source .env

    if pg_isready -d "\$DATABASE_URL" > /dev/null 2>&1; then
        echo "✅ \$env database connectivity working"
    else
        echo "❌ \$env database connectivity failed"
    fi
done

# Test 3: Container status
echo "3. Testing container status..."
for env in production staging development; do
    RUNNING_CONTAINERS=\$(docker ps --filter "name=\$env" --format "{{.Names}}" | wc -l)
    echo "📊 \$env environment: \$RUNNING_CONTAINERS containers running"
done

# Test 4: Resource isolation
echo "4. Testing resource isolation..."
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" | grep -E "(production|staging|development)"

# Test 5: Health check API
echo "5. Testing health check API..."
if curl -f "http://localhost:9999/health/all" > /dev/null 2>&1; then
    echo "✅ Health check API working"
    curl -s "http://localhost:9999/health/all" | python3 -m json.tool
else
    echo "❌ Health check API not working"
fi

echo "=== Environment Testing Completed ==="
EOF

chmod +x ~/test-environments.sh
./test-environments.sh
```

## 🎉 What You've Accomplished

Congratulations! You now have a sophisticated multi-environment setup with:

✅ **Environment Isolation**: Separate production, staging, and development environments  
✅ **Branch-Based Deployment**: Automatic deployments based on Git branches  
✅ **Resource Management**: Proper resource allocation and limits per environment  
✅ **Database Isolation**: Separate databases with environment-specific users  
✅ **Network Segmentation**: Isolated networks for security  
✅ **Promotion Workflows**: Safe promotion between environments  
✅ **Comprehensive Monitoring**: Multi-environment monitoring and alerting  
✅ **Data Synchronization**: Tools for syncing data between environments

### Environment Summary

| Environment | Branch  | Port | Database          | Network             |
| ----------- | ------- | ---- | ----------------- | ------------------- |
| Production  | main    | 8000 | myapp_production  | production-network  |
| Staging     | staging | 8100 | myapp_staging     | staging-network     |
| Development | develop | 8200 | myapp_development | development-network |

## 🔗 Quick Reference Commands

```bash
# Deploy to specific environment
cd ~/environments/production && ./deploy.sh production
cd ~/environments/staging && ./deploy.sh staging
cd ~/environments/development && ./deploy.sh development

# Promote between environments
./promote-environment.sh development staging
./promote-environment.sh staging production

# Monitor all environments
./monitor-environments.sh
curl http://localhost:9999/health/all

# Sync data (development/staging only)
./sync-data.sh production staging database

# Test all environments
./test-environments.sh

# Check specific environment
curl http://localhost:8000/health  # Production
curl http://localhost:8100/health  # Staging
curl http://localhost:8200/health  # Development
```

## 🔮 Coming Up in Part 6

In the final part of our series, we'll:

- Configure custom domains and subdomains
- Set up DNS with Namecheap
- Implement SSL certificates with Let's Encrypt
- Configure domain-based routing
- Set up CDN and performance optimization
- Implement domain monitoring and management

---

_Ready to make your applications accessible via custom domains? Let's set up professional domain management!_

**Next**: [Digital Ocean Mastery Part 6: Custom Domains with Namecheap DNS](/blog/digital-ocean-part-6-custom-domains-namecheap)

---

## Digital Ocean Mastery Part 6: Custom Domains with Namecheap DNS

Configure custom domains and subdomains for your Digital Ocean applications using Namecheap as DNS provider. SSL certificates, domain management, and best practices.

- Canonical page: https://joshua-ansah.vercel.app/blog/digital-ocean-part-6-custom-domains-namecheap
- Author: Joshua Ansah
- Published: September 13, 2025
- Category: DevOps
- Topics: Custom Domains, Namecheap, DNS, SSL, Subdomains, Digital Ocean

Welcome to the final part of our Digital Ocean mastery series! We'll now configure custom domains and subdomains using Namecheap as our DNS provider, implement SSL certificates, and set up professional domain management for all our environments.

## 🎯 What You'll Learn

In this comprehensive guide, we'll cover:

- Domain and subdomain configuration with Namecheap
- DNS records setup and management
- SSL certificate implementation with Let's Encrypt
- Nginx configuration for multiple domains
- Domain-based environment routing
- CDN setup and performance optimization
- Domain monitoring and renewal automation
- Professional email setup (bonus)

## 📋 Prerequisites

Before starting, ensure you have:

- Completed [Parts 1-5](/blog/digital-ocean-part-1-droplet-storage-setup) of this series
- A domain name purchased from Namecheap (or any provider)
- Access to your domain's DNS management
- Understanding of DNS concepts (A, CNAME, MX records)

## 🏗️ Step 1: Domain Strategy Planning

### Domain Structure Planning

Let's plan our domain structure for all environments:

```bash
# Example domain structure:
# yourdomain.com -> Production
# staging.yourdomain.com -> Staging
# dev.yourdomain.com -> Development
# api.yourdomain.com -> API Gateway
# admin.yourdomain.com -> Admin Panel

# Create domain planning document
cat > ~/domain-plan.md <<EOF
# Domain Configuration Plan

## Primary Domain: yourdomain.com
- **Environment**: Production
- **Port**: 80/443
- **Container**: production-app
- **SSL**: Let's Encrypt

## Subdomains:

### staging.yourdomain.com
- **Environment**: Staging
- **Port**: 8101 (internal), 80/443 (external)
- **Container**: staging-app
- **SSL**: Let's Encrypt

### dev.yourdomain.com
- **Environment**: Development
- **Port**: 8201 (internal), 80/443 (external)
- **Container**: development-app
- **SSL**: Let's Encrypt

### api.yourdomain.com
- **Purpose**: API Gateway
- **Routes**: Load balancer for all API endpoints
- **SSL**: Let's Encrypt

### admin.yourdomain.com
- **Purpose**: Administrative interface
- **Security**: IP whitelist, basic auth
- **SSL**: Let's Encrypt

### www.yourdomain.com
- **Purpose**: Redirect to main domain
- **SSL**: Let's Encrypt
EOF
```

## 🌐 Step 2: Namecheap DNS Configuration

### Setting Up DNS Records

1. **Log into Namecheap**:

   - Go to [Namecheap.com](https://namecheap.com)
   - Navigate to Domain List > Manage > Advanced DNS

2. **Configure A Records**:

```bash
# DNS Records to add in Namecheap:

# A Records (point to your droplet IP)
Type: A Record, Host: @, Value: YOUR_DROPLET_IP, TTL: 300
Type: A Record, Host: www, Value: YOUR_DROPLET_IP, TTL: 300
Type: A Record, Host: staging, Value: YOUR_DROPLET_IP, TTL: 300
Type: A Record, Host: dev, Value: YOUR_DROPLET_IP, TTL: 300
Type: A Record, Host: api, Value: YOUR_DROPLET_IP, TTL: 300
Type: A Record, Host: admin, Value: YOUR_DROPLET_IP, TTL: 300

# Optional: AAAA Records for IPv6 (if you have IPv6)
Type: AAAA Record, Host: @, Value: YOUR_DROPLET_IPv6, TTL: 300
```

### Create DNS Management Script

```bash
# Create DNS monitoring script
cat > ~/dns-check.sh <<EOF
#!/bin/bash

DOMAIN="yourdomain.com"
DROPLET_IP="YOUR_DROPLET_IP"

echo "=== DNS Configuration Check ==="
echo "Date: \$(date)"
echo "Domain: \$DOMAIN"
echo "Expected IP: \$DROPLET_IP"
echo

# Check main domain
echo "Checking main domain..."
RESOLVED_IP=\$(dig +short \$DOMAIN)
if [ "\$RESOLVED_IP" = "\$DROPLET_IP" ]; then
    echo "✅ \$DOMAIN resolves correctly to \$DROPLET_IP"
else
    echo "❌ \$DOMAIN resolves to \$RESOLVED_IP (expected \$DROPLET_IP)"
fi

# Check subdomains
for subdomain in www staging dev api admin; do
    echo "Checking \$subdomain.\$DOMAIN..."
    RESOLVED_IP=\$(dig +short \$subdomain.\$DOMAIN)
    if [ "\$RESOLVED_IP" = "\$DROPLET_IP" ]; then
        echo "✅ \$subdomain.\$DOMAIN resolves correctly"
    else
        echo "❌ \$subdomain.\$DOMAIN resolves to \$RESOLVED_IP"
    fi
done

echo
echo "=== DNS Propagation Status ==="
echo "Note: DNS changes can take up to 48 hours to fully propagate"
EOF

chmod +x ~/dns-check.sh
```

## 🔒 Step 3: SSL Certificate Setup with Let's Encrypt

### Install Certbot

```bash
# Install Certbot for Let's Encrypt
sudo apt update
sudo apt install -y certbot python3-certbot-nginx

# Create certificate directory
sudo mkdir -p /mnt/app-data/ssl-certs
sudo chown deploy:deploy /mnt/app-data/ssl-certs
```

### Generate SSL Certificates

```bash
# Create SSL certificate generation script
cat > ~/generate-ssl.sh <<EOF
#!/bin/bash

set -e

DOMAIN="yourdomain.com"
EMAIL="your-email@\$DOMAIN"

echo "Generating SSL certificates for \$DOMAIN and subdomains..."

# Stop nginx temporarily for standalone mode
sudo systemctl stop nginx 2>/dev/null || true
docker stop production-nginx staging-nginx 2>/dev/null || true

# Generate certificates for main domain and all subdomains
sudo certbot certonly --standalone \
    --email \$EMAIL \
    --agree-tos \
    --no-eff-email \
    -d \$DOMAIN \
    -d www.\$DOMAIN \
    -d staging.\$DOMAIN \
    -d dev.\$DOMAIN \
    -d api.\$DOMAIN \
    -d admin.\$DOMAIN

# Copy certificates to our managed location
sudo cp -r /etc/letsencrypt/live/\$DOMAIN /mnt/app-data/ssl-certs/
sudo chown -R deploy:deploy /mnt/app-data/ssl-certs/

echo "SSL certificates generated successfully!"
echo "Certificates location: /mnt/app-data/ssl-certs/\$DOMAIN/"

# Create renewal script
cat > ~/renew-ssl.sh <<EOL
#!/bin/bash
echo "Renewing SSL certificates..."

# Stop services
docker-compose -f ~/environments/production/docker-compose.yml stop nginx
docker-compose -f ~/environments/staging/docker-compose.yml stop nginx

# Renew certificates
sudo certbot renew --standalone

# Copy renewed certificates
sudo cp -r /etc/letsencrypt/live/\$DOMAIN /mnt/app-data/ssl-certs/
sudo chown -R deploy:deploy /mnt/app-data/ssl-certs/

# Restart services
docker-compose -f ~/environments/production/docker-compose.yml start nginx
docker-compose -f ~/environments/staging/docker-compose.yml start nginx

echo "SSL certificates renewed successfully!"
EOL

chmod +x ~/renew-ssl.sh

# Add to crontab for automatic renewal (runs twice daily)
(crontab -l 2>/dev/null; echo "0 2,14 * * * /home/deploy/renew-ssl.sh >> /mnt/app-data/logs/ssl-renewal.log 2>&1") | crontab -

echo "SSL renewal scheduled in crontab"
EOF

chmod +x ~/generate-ssl.sh

# Wait for DNS propagation before running
echo "Please wait for DNS propagation (15-30 minutes) before running:"
echo "./generate-ssl.sh"
```

## 🌐 Step 4: Advanced Nginx Configuration

### Create Master Nginx Configuration

```bash
# Create comprehensive nginx configuration
cat > ~/nginx-master.conf <<EOF
# Main Nginx Configuration for Multi-Domain Setup

# Global settings
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    # Basic settings
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging format
    log_format main '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                    '\$status \$body_bytes_sent "\$http_referer" '
                    '"\$http_user_agent" "\$http_x_forwarded_for" '
                    'rt=\$request_time uct="\$upstream_connect_time" '
                    'uht="\$upstream_header_time" urt="\$upstream_response_time"';

    access_log /var/log/nginx/access.log main;

    # Performance settings
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    client_max_body_size 50M;
    client_body_timeout 60s;
    client_header_timeout 60s;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;

    # Security headers
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self'; font-src 'self'; object-src 'none'; media-src 'self'; frame-src 'none';" always;

    # Rate limiting
    limit_req_zone \$binary_remote_addr zone=general:10m rate=10r/s;
    limit_req_zone \$binary_remote_addr zone=api:10m rate=30r/s;
    limit_req_zone \$binary_remote_addr zone=admin:10m rate=2r/s;

    # Upstream definitions
    upstream production_app {
        server 127.0.0.1:8000;
        keepalive 32;
    }

    upstream staging_app {
        server 127.0.0.1:8100;
        keepalive 16;
    }

    upstream development_app {
        server 127.0.0.1:8200;
        keepalive 8;
    }

    # HTTP to HTTPS redirect
    server {
        listen 80;
        server_name yourdomain.com www.yourdomain.com staging.yourdomain.com dev.yourdomain.com api.yourdomain.com admin.yourdomain.com;
        return 301 https://\$server_name\$request_uri;
    }

    # Production - yourdomain.com
    server {
        listen 443 ssl http2;
        server_name yourdomain.com;

        # SSL configuration
        ssl_certificate /etc/ssl/certs/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/yourdomain.com/privkey.pem;
        ssl_session_timeout 1d;
        ssl_session_cache shared:SSL:50m;
        ssl_session_tickets off;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;

        # HSTS
        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

        # Rate limiting
        limit_req zone=general burst=20 nodelay;

        location / {
            proxy_pass http://production_app;
            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;
            proxy_set_header X-Forwarded-Host \$host;
            proxy_set_header X-Forwarded-Port \$server_port;

            # Timeouts
            proxy_connect_timeout 60s;
            proxy_send_timeout 60s;
            proxy_read_timeout 60s;

            # Buffering
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 8 4k;
        }

        # Health check endpoint
        location /health {
            proxy_pass http://production_app;
            access_log off;
        }

        # Static files caching
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)\$ {
            proxy_pass http://production_app;
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    }

    # WWW redirect to non-WWW
    server {
        listen 443 ssl http2;
        server_name www.yourdomain.com;

        ssl_certificate /etc/ssl/certs/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/yourdomain.com/privkey.pem;

        return 301 https://yourdomain.com\$request_uri;
    }

    # Staging - staging.yourdomain.com
    server {
        listen 443 ssl http2;
        server_name staging.yourdomain.com;

        ssl_certificate /etc/ssl/certs/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/yourdomain.com/privkey.pem;

        # Basic auth for staging (optional)
        # auth_basic "Staging Environment";
        # auth_basic_user_file /etc/nginx/.htpasswd;

        limit_req zone=general burst=10 nodelay;

        location / {
            proxy_pass http://staging_app;
            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;
        }
    }

    # Development - dev.yourdomain.com
    server {
        listen 443 ssl http2;
        server_name dev.yourdomain.com;

        ssl_certificate /etc/ssl/certs/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/yourdomain.com/privkey.pem;

        # IP whitelist for development (adjust IPs)
        allow 127.0.0.1;
        allow YOUR_OFFICE_IP;
        allow YOUR_HOME_IP;
        deny all;

        location / {
            proxy_pass http://development_app;
            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;
        }
    }

    # API Gateway - api.yourdomain.com
    server {
        listen 443 ssl http2;
        server_name api.yourdomain.com;

        ssl_certificate /etc/ssl/certs/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/yourdomain.com/privkey.pem;

        limit_req zone=api burst=50 nodelay;

        # CORS headers for API
        add_header Access-Control-Allow-Origin "*" always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization" always;

        # Handle preflight requests
        if (\$request_method = 'OPTIONS') {
            return 204;
        }

        # API versioning
        location /v1/ {
            proxy_pass http://production_app/api/v1/;
            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;
        }

        # Default to latest API version
        location / {
            proxy_pass http://production_app/api/;
            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;
        }
    }

    # Admin Panel - admin.yourdomain.com
    server {
        listen 443 ssl http2;
        server_name admin.yourdomain.com;

        ssl_certificate /etc/ssl/certs/yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/yourdomain.com/privkey.pem;

        # IP whitelist for admin panel
        allow YOUR_OFFICE_IP;
        allow YOUR_HOME_IP;
        deny all;

        # Basic authentication
        auth_basic "Admin Panel";
        auth_basic_user_file /etc/nginx/.htpasswd;

        limit_req zone=admin burst=5 nodelay;

        location / {
            proxy_pass http://production_app/admin/;
            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;
        }
    }
}
EOF
```

### Create Basic Auth for Admin Panel

```bash
# Install apache2-utils for htpasswd
sudo apt install -y apache2-utils

# Create basic auth file
sudo htpasswd -c /etc/nginx/.htpasswd admin

# Set proper permissions
sudo chmod 644 /etc/nginx/.htpasswd
```

### Deploy Nginx Configuration

```bash
# Create nginx deployment script
cat > ~/deploy-nginx.sh <<EOF
#!/bin/bash

set -e

echo "Deploying nginx configuration..."

# Backup current configuration
if [ -f /etc/nginx/nginx.conf ]; then
    sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup.\$(date +%Y%m%d_%H%M%S)
fi

# Deploy new configuration
sudo cp ~/nginx-master.conf /etc/nginx/nginx.conf

# Create SSL certificate directory in nginx
sudo mkdir -p /etc/ssl/certs
sudo ln -sf /mnt/app-data/ssl-certs/yourdomain.com /etc/ssl/certs/yourdomain.com

# Test configuration
if sudo nginx -t; then
    echo "✅ Nginx configuration is valid"

    # Reload nginx
    if sudo systemctl is-active nginx > /dev/null; then
        sudo systemctl reload nginx
        echo "✅ Nginx reloaded successfully"
    else
        sudo systemctl start nginx
        echo "✅ Nginx started successfully"
    fi
else
    echo "❌ Nginx configuration is invalid"

    # Restore backup if available
    if [ -f /etc/nginx/nginx.conf.backup.* ]; then
        LATEST_BACKUP=\$(ls -t /etc/nginx/nginx.conf.backup.* | head -1)
        sudo cp "\$LATEST_BACKUP" /etc/nginx/nginx.conf
        echo "Restored backup configuration"
    fi
    exit 1
fi

echo "Nginx deployment completed!"
EOF

chmod +x ~/deploy-nginx.sh
```

## 📊 Step 5: Domain Monitoring and Management

### Create Domain Health Monitoring

```bash
# Create comprehensive domain monitoring script
cat > ~/monitor-domains.sh <<EOF
#!/bin/bash

DOMAIN="yourdomain.com"
LOG_FILE="/mnt/app-data/logs/domain-monitor.log"

echo "=== Domain Health Monitor - \$(date) ===" >> \$LOG_FILE

# Domains to monitor
DOMAINS=(
    "yourdomain.com"
    "www.yourdomain.com"
    "staging.yourdomain.com"
    "dev.yourdomain.com"
    "api.yourdomain.com"
    "admin.yourdomain.com"
)

# Check each domain
for domain in "\${DOMAINS[@]}"; do
    echo "--- Checking \$domain ---" >> \$LOG_FILE

    # SSL certificate check
    SSL_EXPIRY=\$(echo | openssl s_client -servername \$domain -connect \$domain:443 2>/dev/null | openssl x509 -noout -dates 2>/dev/null | grep notAfter | cut -d= -f2)

    if [ -n "\$SSL_EXPIRY" ]; then
        SSL_EXPIRY_EPOCH=\$(date -d "\$SSL_EXPIRY" +%s)
        CURRENT_EPOCH=\$(date +%s)
        DAYS_UNTIL_EXPIRY=\$(( (SSL_EXPIRY_EPOCH - CURRENT_EPOCH) / 86400 ))

        echo "🔒 SSL expires in \$DAYS_UNTIL_EXPIRY days (\$SSL_EXPIRY)" >> \$LOG_FILE

        # Alert if expiring soon
        if [ \$DAYS_UNTIL_EXPIRY -lt 30 ]; then
            echo "⚠️  SSL WARNING: Certificate expires in \$DAYS_UNTIL_EXPIRY days!" >> \$LOG_FILE
        fi
    else
        echo "❌ SSL: Unable to retrieve certificate info" >> \$LOG_FILE
    fi

    # HTTP response check
    HTTP_STATUS=\$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://\$domain/health" || echo "000")

    if [ "\$HTTP_STATUS" = "200" ]; then
        echo "✅ HTTP: \$HTTP_STATUS (OK)" >> \$LOG_FILE
    else
        echo "❌ HTTP: \$HTTP_STATUS (Error)" >> \$LOG_FILE
    fi

    # Response time check
    RESPONSE_TIME=\$(curl -s -o /dev/null -w "%{time_total}" --max-time 10 "https://\$domain/health" || echo "timeout")
    echo "⏱️  Response time: \${RESPONSE_TIME}s" >> \$LOG_FILE

    # DNS resolution check
    DNS_IP=\$(dig +short \$domain | head -1)
    echo "🌐 DNS resolves to: \$DNS_IP" >> \$LOG_FILE

    echo "" >> \$LOG_FILE
done

echo "================================" >> \$LOG_FILE
echo "" >> \$LOG_FILE
EOF

chmod +x ~/monitor-domains.sh

# Add to crontab for regular monitoring
crontab -e
# Add: */30 * * * * /home/deploy/monitor-domains.sh
```

### SSL Certificate Monitoring

```bash
# Create SSL monitoring and alert script
cat > ~/ssl-monitor.sh <<EOF
#!/bin/bash

DOMAIN="yourdomain.com"
ALERT_DAYS=14
EMAIL="your-email@\$DOMAIN"

# Check SSL certificate expiry
SSL_EXPIRY=\$(echo | openssl s_client -servername \$DOMAIN -connect \$DOMAIN:443 2>/dev/null | openssl x509 -noout -dates 2>/dev/null | grep notAfter | cut -d= -f2)

if [ -n "\$SSL_EXPIRY" ]; then
    SSL_EXPIRY_EPOCH=\$(date -d "\$SSL_EXPIRY" +%s)
    CURRENT_EPOCH=\$(date +%s)
    DAYS_UNTIL_EXPIRY=\$(( (SSL_EXPIRY_EPOCH - CURRENT_EPOCH) / 86400 ))

    echo "SSL certificate for \$DOMAIN expires in \$DAYS_UNTIL_EXPIRY days"

    if [ \$DAYS_UNTIL_EXPIRY -lt \$ALERT_DAYS ]; then
        echo "WARNING: SSL certificate expires in \$DAYS_UNTIL_EXPIRY days!"
        echo "Certificate expires on: \$SSL_EXPIRY"

        # Log alert
        echo "\$(date): SSL WARNING - Certificate expires in \$DAYS_UNTIL_EXPIRY days" >> /mnt/app-data/logs/ssl-alerts.log

        # Here you could send email alerts or Slack notifications
        # Example: echo "SSL Alert for \$DOMAIN" | mail -s "SSL Expiry Warning" \$EMAIL
    fi
else
    echo "ERROR: Unable to retrieve SSL certificate information for \$DOMAIN"
    echo "\$(date): SSL ERROR - Unable to retrieve certificate for \$DOMAIN" >> /mnt/app-data/logs/ssl-alerts.log
fi
EOF

chmod +x ~/ssl-monitor.sh

# Add to crontab for daily SSL monitoring
crontab -e
# Add: 0 9 * * * /home/deploy/ssl-monitor.sh
```

## 🚀 Step 6: Performance Optimization with CDN

### Cloudflare Integration (Optional)

````bash
# Create Cloudflare optimization guide
cat > ~/cloudflare-setup.md <<EOF
# Cloudflare CDN Setup Guide

## Steps to integrate Cloudflare:

1. **Sign up for Cloudflare**
   - Go to cloudflare.com
   - Add your domain
   - Follow DNS migration instructions

2. **DNS Configuration**
   - Import existing DNS records
   - Ensure all A records point to your droplet
   - Enable Cloudflare proxy (orange cloud) for web traffic

3. **SSL/TLS Settings**
   - Set SSL/TLS encryption mode to "Full (strict)"
   - Enable "Always Use HTTPS"
   - Enable "Automatic HTTPS Rewrites"

4. **Performance Settings**
   - Enable "Auto Minify" for CSS, JavaScript, HTML
   - Set "Browser Cache TTL" to "Respect Existing Headers"
   - Enable "Brotli" compression

5. **Security Settings**
   - Set Security Level to "Medium"
   - Enable "Browser Integrity Check"
   - Configure firewall rules if needed

6. **Page Rules** (if using Cloudflare)
   - Cache Everything for static assets
   - Bypass cache for API endpoints
   - Force HTTPS for all pages

## Nginx Headers for Cloudflare

Add these headers to nginx for optimal Cloudflare integration:

```nginx
# Cloudflare real IP
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
real_ip_header CF-Connecting-IP;
````

EOF

````

### Performance Testing Script

```bash
# Create performance testing script
cat > ~/performance-test.sh <<EOF
#!/bin/bash

DOMAIN="yourdomain.com"
LOG_FILE="/mnt/app-data/logs/performance-test.log"

echo "=== Performance Test - \$(date) ===" >> \$LOG_FILE

# Test main domain
echo "Testing https://\$DOMAIN" >> \$LOG_FILE

# Test load time
LOAD_TIME=\$(curl -s -o /dev/null -w "%{time_total}" "https://\$DOMAIN")
echo "Load time: \${LOAD_TIME}s" >> \$LOG_FILE

# Test Time to First Byte
TTFB=\$(curl -s -o /dev/null -w "%{time_starttransfer}" "https://\$DOMAIN")
echo "TTFB: \${TTFB}s" >> \$LOG_FILE

# Test DNS lookup time
DNS_TIME=\$(curl -s -o /dev/null -w "%{time_namelookup}" "https://\$DOMAIN")
echo "DNS lookup: \${DNS_TIME}s" >> \$LOG_FILE

# Test SSL handshake time
SSL_TIME=\$(curl -s -o /dev/null -w "%{time_appconnect}" "https://\$DOMAIN")
echo "SSL handshake: \${SSL_TIME}s" >> \$LOG_FILE

# Test different endpoints
ENDPOINTS=("/health" "/api/status" "/")

for endpoint in "\${ENDPOINTS[@]}"; do
    echo "Testing endpoint: \$endpoint" >> \$LOG_FILE

    RESPONSE_TIME=\$(curl -s -o /dev/null -w "%{time_total}" "https://\$DOMAIN\$endpoint")
    HTTP_CODE=\$(curl -s -o /dev/null -w "%{http_code}" "https://\$DOMAIN\$endpoint")

    echo "  Response time: \${RESPONSE_TIME}s, HTTP code: \$HTTP_CODE" >> \$LOG_FILE
done

echo "================================" >> \$LOG_FILE
echo "" >> \$LOG_FILE
EOF

chmod +x ~/performance-test.sh

# Add to crontab for regular performance monitoring
crontab -e
# Add: 0 */6 * * * /home/deploy/performance-test.sh
````

## 📧 Step 7: Professional Email Setup (Bonus)

### Email DNS Records

```bash
# Add these MX records in Namecheap for professional email
# (adjust based on your email provider)

# For Google Workspace:
Type: MX Record, Host: @, Value: 1 aspmx.l.google.com., TTL: 300
Type: MX Record, Host: @, Value: 5 alt1.aspmx.l.google.com., TTL: 300
Type: MX Record, Host: @, Value: 5 alt2.aspmx.l.google.com., TTL: 300
Type: MX Record, Host: @, Value: 10 alt3.aspmx.l.google.com., TTL: 300
Type: MX Record, Host: @, Value: 10 alt4.aspmx.l.google.com., TTL: 300

# SPF Record (TXT)
Type: TXT Record, Host: @, Value: "v=spf1 include:_spf.google.com ~all", TTL: 300

# DKIM Record (TXT) - Get this from your email provider
Type: TXT Record, Host: google._domainkey, Value: "v=DKIM1; k=rsa; p=YOUR_DKIM_KEY", TTL: 300

# DMARC Record (TXT)
Type: TXT Record, Host: _dmarc, Value: "v=DMARC1; p=quarantine; rua=mailto:dmarc@yourdomain.com", TTL: 300
```

## ✅ Step 8: Final Testing and Validation

### Comprehensive Domain Test

```bash
# Create final validation script
cat > ~/validate-setup.sh <<EOF
#!/bin/bash

DOMAIN="yourdomain.com"

echo "=== Final Domain Setup Validation ==="
echo "Date: \$(date)"
echo "Domain: \$DOMAIN"
echo

# Test 1: DNS Resolution
echo "1. Testing DNS resolution..."
for subdomain in "" "www" "staging" "dev" "api" "admin"; do
    if [ -z "\$subdomain" ]; then
        test_domain="\$DOMAIN"
    else
        test_domain="\$subdomain.\$DOMAIN"
    fi

    IP=\$(dig +short \$test_domain)
    if [ -n "\$IP" ]; then
        echo "✅ \$test_domain resolves to \$IP"
    else
        echo "❌ \$test_domain does not resolve"
    fi
done

# Test 2: SSL Certificates
echo
echo "2. Testing SSL certificates..."
for subdomain in "" "www" "staging" "dev" "api" "admin"; do
    if [ -z "\$subdomain" ]; then
        test_domain="\$DOMAIN"
    else
        test_domain="\$subdomain.\$DOMAIN"
    fi

    if echo | openssl s_client -servername \$test_domain -connect \$test_domain:443 2>/dev/null | openssl x509 -noout -subject > /dev/null 2>&1; then
        echo "✅ \$test_domain SSL certificate is valid"
    else
        echo "❌ \$test_domain SSL certificate is invalid or missing"
    fi
done

# Test 3: HTTP/HTTPS Redirects
echo
echo "3. Testing HTTP to HTTPS redirects..."
for subdomain in "" "www" "staging" "dev"; do
    if [ -z "\$subdomain" ]; then
        test_domain="\$DOMAIN"
    else
        test_domain="\$subdomain.\$DOMAIN"
    fi

    REDIRECT=\$(curl -s -o /dev/null -w "%{redirect_url}" "http://\$test_domain")
    if [[ "\$REDIRECT" == https://* ]]; then
        echo "✅ \$test_domain redirects to HTTPS"
    else
        echo "❌ \$test_domain does not redirect to HTTPS properly"
    fi
done

# Test 4: Application Health
echo
echo "4. Testing application health..."
HEALTH_ENDPOINTS=(
    "https://\$DOMAIN/health:Production"
    "https://staging.\$DOMAIN/health:Staging"
    "https://dev.\$DOMAIN/health:Development"
)

for endpoint_info in "\${HEALTH_ENDPOINTS[@]}"; do
    IFS=':' read -r endpoint name <<< "\$endpoint_info"

    HTTP_CODE=\$(curl -s -o /dev/null -w "%{http_code}" "\$endpoint")
    if [ "\$HTTP_CODE" = "200" ]; then
        echo "✅ \$name (\$endpoint) is healthy"
    else
        echo "❌ \$name (\$endpoint) returned HTTP \$HTTP_CODE"
    fi
done

# Test 5: Performance check
echo
echo "5. Testing performance..."
LOAD_TIME=\$(curl -s -o /dev/null -w "%{time_total}" "https://\$DOMAIN")
echo "📊 Main domain load time: \${LOAD_TIME}s"

if (( \$(echo "\$LOAD_TIME < 2.0" | bc -l) )); then
    echo "✅ Performance is good (< 2s)"
else
    echo "⚠️  Performance could be improved (> 2s)"
fi

echo
echo "=== Validation Complete ==="
echo "Check /mnt/app-data/logs/ for detailed monitoring logs"
EOF

chmod +x ~/validate-setup.sh
./validate-setup.sh
```

## 🎉 What You've Accomplished

Congratulations! You have completed the entire Digital Ocean mastery series with a professional domain setup:

✅ **Custom Domains**: Professional domain configuration with Namecheap DNS  
✅ **SSL Certificates**: Automated Let's Encrypt certificates with auto-renewal  
✅ **Multi-Environment Domains**: Separate subdomains for production, staging, and development  
✅ **Advanced Nginx**: High-performance reverse proxy with security headers  
✅ **Domain Monitoring**: Automated monitoring of SSL, DNS, and performance  
✅ **Performance Optimization**: CDN-ready configuration and performance testing  
✅ **Professional Email**: DNS records for professional email setup  
✅ **Security Features**: IP whitelisting, basic auth, and security headers

## 🌐 Final Domain Architecture

| Domain                 | Environment | Purpose                 | Security                      |
| ---------------------- | ----------- | ----------------------- | ----------------------------- |
| yourdomain.com         | Production  | Main application        | SSL, Security headers         |
| www.yourdomain.com     | Production  | Redirect to main        | SSL redirect                  |
| staging.yourdomain.com | Staging     | Staging environment     | SSL, Optional basic auth      |
| dev.yourdomain.com     | Development | Development environment | SSL, IP whitelist             |
| api.yourdomain.com     | Production  | API gateway             | SSL, CORS, Rate limiting      |
| admin.yourdomain.com   | Production  | Admin panel             | SSL, IP whitelist, Basic auth |

## 🔗 Quick Reference Commands

```bash
# Domain and SSL management
./dns-check.sh                    # Check DNS resolution
./generate-ssl.sh                 # Generate SSL certificates
./renew-ssl.sh                     # Renew SSL certificates
./deploy-nginx.sh                  # Deploy nginx configuration

# Monitoring
./monitor-domains.sh               # Monitor all domains
./ssl-monitor.sh                   # Monitor SSL certificates
./performance-test.sh              # Test performance
./validate-setup.sh                # Complete validation

# Manual SSL renewal
sudo certbot renew --standalone

# Check nginx configuration
sudo nginx -t
sudo systemctl reload nginx

# View logs
tail -f /mnt/app-data/logs/domain-monitor.log
tail -f /mnt/app-data/logs/ssl-alerts.log
tail -f /var/log/nginx/access.log
```

## 📚 Complete Series Summary

Over the course of this 6-part series, you have built:

1. **Part 1**: Secure droplet with block storage and basic security
2. **Part 2**: PostgreSQL database with secure remote access
3. **Part 3**: Docker containerization with monitoring and management
4. **Part 4**: Node.js deployment with GitHub Actions CI/CD
5. **Part 5**: Multi-environment setup with branch-based deployments
6. **Part 6**: Professional domain management with SSL and monitoring

## 🚀 What's Next?

Your infrastructure is now production-ready! Consider these advanced topics:

- **Kubernetes**: Scale beyond single-server deployments
- **Monitoring Stack**: Implement Prometheus, Grafana, and alerting
- **Backup Strategies**: Automated backups with retention policies
- **Security Hardening**: Implement WAF, DDoS protection, and security scanning
- **Performance Optimization**: Database tuning, caching strategies, and CDN
- **Disaster Recovery**: Multi-region deployments and failover strategies

---

_Congratulations on completing the Digital Ocean mastery series! You now have a professional, scalable, and secure infrastructure ready for production workloads._

**Have questions or want to share your setup?** Feel free to reach out! 🚀

