{"id":22796385,"url":"https://github.com/atulkamble/dockerfile-examples","last_synced_at":"2025-03-30T18:15:08.644Z","repository":{"id":264986277,"uuid":"862275416","full_name":"atulkamble/Dockerfile-Examples","owner":"atulkamble","description":"This repository contains a collection of advanced Dockerfile examples for various types of applications, demonstrating best practices, multi-stage builds, optimizations, and configurations. These examples can be used as a reference for building and deploying applications using Docker in production environments.","archived":false,"fork":false,"pushed_at":"2024-09-24T14:35:04.000Z","size":87,"stargazers_count":0,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-28T02:51:49.282Z","etag":null,"topics":["docker","dockerfile"],"latest_commit_sha":null,"homepage":"","language":"Dockerfile","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/atulkamble.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-24T10:29:26.000Z","updated_at":"2024-09-24T14:35:08.000Z","dependencies_parsed_at":"2024-11-27T06:31:57.809Z","dependency_job_id":null,"html_url":"https://github.com/atulkamble/Dockerfile-Examples","commit_stats":null,"previous_names":["atulkamble/dockerfile-examples"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atulkamble%2FDockerfile-Examples","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atulkamble%2FDockerfile-Examples/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atulkamble%2FDockerfile-Examples/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/atulkamble%2FDockerfile-Examples/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/atulkamble","download_url":"https://codeload.github.com/atulkamble/Dockerfile-Examples/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246358321,"owners_count":20764366,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["docker","dockerfile"],"created_at":"2024-12-12T05:12:44.897Z","updated_at":"2025-03-30T18:15:08.617Z","avatar_url":"https://github.com/atulkamble.png","language":"Dockerfile","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Dockerfile-Examples\n\nHere's the suggested structure for your repository on Dockerfile examples:\n\nLet me know if you'd like further refinements or additions to the repo structure!\n\nHere's a step-by-step guide on creating `Dockerfile` examples and setting them up on an EC2 instance:\n\n---\n\n### **Setting Up Docker and Running Docker Containers on EC2**\n\n#### **1. Launch an EC2 Instance**\n1. Go to your AWS Management Console.\n2. Launch a new EC2 instance using an Amazon Linux 2\n3. Choose instance type (e.g., t2.micro).\n4. Create keypair and select | key.pem\n5. Configure SG - security groups:\n   - Allow Inbound | SSH - 22, HTTP - 80, HTTPS - 443, FLASK- 5000, NodeJS - 3000\n\n#### **2. Connect to the EC2 Instance**\n\n1. SSH into your EC2 instance:\n   ```bash\n   cd Downloads\n   chmod 400 key.pem\n   ssh -i your-key.pem ec2-user@\u003cec2-public-ip\u003e\n   example: ssh -i \"key.pem\" ec2-user@ec2-52-90-17-121.compute-1.amazonaws.com\n   ```\n\n#### **3. Install Docker on EC2 Instance**\n\nFor **Amazon Linux 2**:\n\n1. Update the package manager:\n   ```bash\n   sudo yum update -y\n   ```\n\n2. Install Docker:\n   ```bash\n   sudo yum install docker -y\n   ```\n\n3. Start Docker service and enable it to run on startup:\n   ```bash\n   sudo systemctl start docker\n   sudo systemctl enable docker\n   ```\n\n4. Add the current user to the `docker` group:\n   ```bash\n   sudo usermod -a -G docker ec2-user\n   ```\n\n\n#### **4. Install Git and Clone Your Application Code**\n\n1. Install Git:\n   ```bash\n   sudo yum install git -y   # Amazon Linux\n   git --version\n   ```\n\n2. Configure Git Credentials\n   ```\n   git config --global user.name \"Atul Kamble\"\n   git config --global user.email \"atul_kamble@hotmail.com\"\n   git config --global credential.helper store\n   nano ~/.git-credentials\n   // copy\n   https://atuljkamble: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@github.com\n   // save\n   git config --global --list\n   ```\n   \n4. Clone your repository containing the Dockerfile and application code:\n   ```bash\n   git clone https://github.com/atulkamble/Dockerfile-Examples.git\n   cd Dockerfile-Examples\n   ```\n   \n### **Topics Covered:**\n1. **Basic Dockerfile Setup**:\n   - Python (Flask)\n   - Node.js (Express)\n   - Java (Spring Boot)\n   - PHP (Laravel)\n   - .NET Core Application\n\n2. **Advanced Dockerfile Techniques**:\n   - Multi-stage builds for optimized image sizes\n   - Caching strategies for faster builds\n   - Running containers as non-root users for security\n   - Health checks for container monitoring\n   - Using build arguments and environment variables\n\n3. **Docker Compose for Multi-Container Applications**:\n   - Setting up multiple services (e.g., Nginx, Node.js, PostgreSQL) using `docker-compose.yml`\n\n4. **Best Practices**:\n   - Image size optimizations\n   - Security considerations\n   - Automated health checks\n   - Auto-restarting containers on failure\n\n---\n\n#### **5. Build the Docker Image**\n\n1. Build the Docker image from the `Dockerfile`:\n   ```bash\n   docker build -t your-app-image .\n   ```\n\n#### **6. Run the Docker Container**\n\n1. Run the Docker container with port forwarding:\n   - For Flask:\n     ```bash\n     docker run -d -p 5000:5000 your-app-image\n     ```\n\n   - For Node.js:\n     ```bash\n     docker run -d -p 3000:3000 your-app-image\n     ```\n\n2. The application will now be accessible via the EC2 public IP on the specified port:\n   - Flask App: `http://\u003cec2-public-ip\u003e:5000`\n   - Node.js App: `http://\u003cec2-public-ip\u003e:3000`\n\n#### **7. (Optional) Auto-start Docker Container on Reboot**\n\nTo ensure the Docker container starts automatically when the EC2 instance reboots, create a `systemd` service for your Docker container.\n\n1. Create a new service file:\n   ```bash\n   sudo nano /etc/systemd/system/myapp.service\n   ```\n\n2. Add the following content:\n   ```ini\n   [Unit]\n   Description=Docker Container for MyApp\n   After=docker.service\n   Requires=docker.service\n\n   [Service]\n   Restart=always\n   ExecStart=/usr/bin/docker start -a \u003ccontainer_name\u003e\n   ExecStop=/usr/bin/docker stop -t 2 \u003ccontainer_name\u003e\n\n   [Install]\n   WantedBy=multi-user.target\n   ```\n\n3. Enable the service:\n   ```bash\n   sudo systemctl enable myapp\n   ```\n\n---\n\nThis setup will get your Docker-based applications running on an EC2 instance. Let me know if you need further customizations for any specific applications or use cases!\n\n\n---\n\n### **1. Dockerfile Example for a Python (Flask) App**\n\n**Dockerfile:**\n\n```Dockerfile\n# Base image\nFROM python:3.9-slim\n\n# Set the working directory\nWORKDIR /app\n\n# Copy the requirements file into the container\nCOPY requirements.txt .\n\n# Install dependencies\nRUN pip install flask\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy application code\nCOPY . .\n\n# Expose the port the app runs on\nEXPOSE 5000\n\n# Set the command to run the app\nCMD [\"python\", \"app.py\"]\n```\n\n**Example Python App (Flask):**\n- `app.py`\n```python\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello():\n    return \"Hello, Flask on Docker!\"\n\nif __name__ == '__main__':\n    app.run(host='0.0.0.0')\n```\n\n- `requirements.txt`\n```\nFlask==2.1.2\n```\n\nThe error you're seeing, `ModuleNotFoundError: No module named 'flask'`, indicates that the Flask module is not installed in your Python environment.\n\nTo resolve this, you can install Flask in your environment using the following steps:\n\n### Step 1: Activate the Correct Python Environment\nIf you are using a virtual environment, activate it first. If not, you can either install Flask globally or create a virtual environment to isolate dependencies.\n\n#### For a virtual environment:\nIf you haven't created a virtual environment, you can do so with:\n```bash\npython3 -m venv venv\n```\n\nActivate the virtual environment:\n```bash\nsource venv/bin/activate\n```\n\n### Step 2: Install Flask\nOnce the environment is active, install Flask:\n```bash\npip install flask\n```\n\n### Step 3: Verify Installation\nEnsure that Flask is installed by checking the installed packages:\n```bash\npip list | grep Flask\n```\n\n### Step 4: Run Your Application Again\nNow, try running your application:\n```bash\npython app.py\n```\n\nThis should resolve the `ModuleNotFoundError` for Flask.\n\n### Step 5: Add Dependencies to `requirements.txt` (Optional but Recommended)\nIf you're deploying this app using Docker or to another environment, make sure you add Flask to a `requirements.txt` file:\n```bash\npip freeze \u003e requirements.txt\n```\n\nIn your `Dockerfile`, ensure you have a step that installs these dependencies:\n```dockerfile\nCOPY requirements.txt .\nRUN pip install -r requirements.txt\n```\n\nLet me know if you need further assistance!\n\n### **2. Dockerfile Example for Node.js (Express) App**\n\n**Dockerfile:**\n\n```Dockerfile\n# Base image\nFROM node:16-alpine\n\n# Set working directory\nWORKDIR /app\n\n# Copy package.json and install dependencies\nCOPY package*.json ./\nRUN npm install --production\n\n# Copy application code\nCOPY . .\n\n# Expose the port the app runs on\nEXPOSE 3000\n\n# Command to run the app\nCMD [\"node\", \"app.js\"]\n```\n\n**Example Node.js App:**\n- `app.js`\n```javascript\nconst express = require('express');\nconst app = express();\n\napp.get('/', (req, res) =\u003e {\n  res.send('Hello, Express on Docker!');\n});\n\napp.listen(3000, () =\u003e {\n  console.log('Server is running on port 3000');\n});\n```\n\n- `package.json`\n```json\n{\n  \"name\": \"docker-node-app\",\n  \"version\": \"1.0.0\",\n  \"main\": \"app.js\",\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  }\n}\n```\nHere are examples of basic `Dockerfile` setups for different types of applications:\n\n### 1. **Python Application (Flask)**\n\n```Dockerfile\n# Base image\nFROM python:3.9-slim\n\n# Set the working directory\nWORKDIR /app\n\n# Copy the requirements file into the container\nCOPY requirements.txt .\n\n# Install the dependencies\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy the rest of the application code\nCOPY . .\n\n# Expose the port the app runs on\nEXPOSE 5000\n\n# Set the command to run the app\nCMD [\"python\", \"app.py\"]\n```\n\n### 2. **Node.js Application (Express)**\n\n```Dockerfile\n# Base image\nFROM node:16-alpine\n\n# Set working directory\nWORKDIR /app\n\n# Copy package.json and install dependencies\nCOPY package*.json ./\nRUN npm install --production\n\n# Copy application code\nCOPY . .\n\n# Expose the port the app runs on\nEXPOSE 3000\n\n# Command to run the application\nCMD [\"node\", \"app.js\"]\n```\n\n### 3. **Java Application (Spring Boot)**\n\n```Dockerfile\n# Base image\nFROM openjdk:17-jdk-slim\n\n# Set the working directory\nWORKDIR /app\n\n# Copy the jar file\nCOPY target/myapp.jar /app/myapp.jar\n\n# Expose port 8080\nEXPOSE 8080\n\n# Run the application\nENTRYPOINT [\"java\", \"-jar\", \"myapp.jar\"]\n```\n\n### 4. **PHP Application (Laravel)**\n\n```Dockerfile\n# Base image\nFROM php:8.1-fpm-alpine\n\n# Set working directory\nWORKDIR /var/www\n\n# Install dependencies\nRUN docker-php-ext-install pdo pdo_mysql\n\n# Copy application code\nCOPY . .\n\n# Install composer and dependencies\nCOPY --from=composer:2 /usr/bin/composer /usr/bin/composer\nRUN composer install --no-dev --optimize-autoloader\n\n# Expose port 9000 for PHP-FPM\nEXPOSE 9000\n\n# Start the PHP-FPM server\nCMD [\"php-fpm\"]\n```\n\n### 5. **.NET Core Application**\n\n```Dockerfile\n# Base image for build\nFROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base\nWORKDIR /app\nEXPOSE 80\n\n# Copy the application files\nFROM mcr.microsoft.com/dotnet/sdk:7.0 AS build\nWORKDIR /src\nCOPY . .\n\n# Restore the dependencies and build the app\nRUN dotnet restore \"MyApp/MyApp.csproj\"\nRUN dotnet build \"MyApp/MyApp.csproj\" -c Release -o /app/build\n\n# Publish the app\nFROM build AS publish\nRUN dotnet publish \"MyApp/MyApp.csproj\" -c Release -o /app/publish\n\n# Create the final image\nFROM base AS final\nWORKDIR /app\nCOPY --from=publish /app/publish .\nENTRYPOINT [\"dotnet\", \"MyApp.dll\"]\n```\n\nThese Dockerfiles demonstrate basic setups. You can modify them based on specific needs such as adding environment variables, using multi-stage builds for optimization, or using custom configurations for the applications.\n\nHere are some **advanced Dockerfile examples** covering various use cases, optimizations, and multi-stage builds for better performance, security, and flexibility.\n\n---\n\n### **1. Python Application with Multi-stage Build and Caching**\n\nThis Dockerfile demonstrates caching Python dependencies and using multi-stage builds for smaller final images.\n\n```Dockerfile\n# Stage 1: Build stage with dependencies\nFROM python:3.9-slim AS builder\n\n# Install pip and set up environment\nRUN apt-get update \u0026\u0026 apt-get install -y build-essential\nWORKDIR /app\n\n# Copy only requirements to leverage Docker caching\nCOPY requirements.txt .\n\n# Install dependencies\nRUN pip install --user --no-cache-dir -r requirements.txt\n\n# Stage 2: Final stage, minimal runtime environment\nFROM python:3.9-slim\n\n# Set environment variables for Python\nENV PATH=/root/.local/bin:$PATH\nENV PYTHONUNBUFFERED=1\n\n# Copy dependencies from build stage\nCOPY --from=builder /root/.local /root/.local\n\n# Copy the application code\nCOPY . /app\nWORKDIR /app\n\n# Expose the port Flask will run on\nEXPOSE 5000\n\n# Command to run the app\nCMD [\"python\", \"app.py\"]\n```\n\n### **2. Node.js Application with Non-root User and Multi-stage Build**\n\nThis Dockerfile sets up a Node.js app and adds security by running the container as a non-root user.\n\n```Dockerfile\n# Stage 1: Build stage\nFROM node:16-alpine AS builder\n\n# Set working directory\nWORKDIR /app\n\n# Copy package.json and install dependencies\nCOPY package*.json ./\nRUN npm install\n\n# Copy application source code\nCOPY . .\n\n# Stage 2: Final stage with non-root user\nFROM node:16-alpine\n\n# Create non-root user\nRUN addgroup -S nodegroup \u0026\u0026 adduser -S nodeuser -G nodegroup\n\n# Set working directory\nWORKDIR /app\n\n# Copy built application code from builder stage\nCOPY --from=builder /app /app\n\n# Change ownership of the application\nRUN chown -R nodeuser:nodegroup /app\n\n# Use non-root user\nUSER nodeuser\n\n# Expose the port the app runs on\nEXPOSE 3000\n\n# Command to run the app\nCMD [\"node\", \"app.js\"]\n```\n\n### **3. Java Application with Multi-stage Build (Maven and JAR)**\n\nThis Dockerfile demonstrates a multi-stage build for a Java Spring Boot application, leveraging Maven for dependency resolution and reducing the final image size.\n\n```Dockerfile\n# Stage 1: Build the application with Maven\nFROM maven:3.8.4-openjdk-17 AS builder\n\n# Set the working directory\nWORKDIR /build\n\n# Copy the pom.xml and resolve dependencies\nCOPY pom.xml .\nRUN mvn dependency:go-offline\n\n# Copy the source code and build the JAR file\nCOPY src ./src\nRUN mvn clean package -DskipTests\n\n# Stage 2: Create the final image with JRE\nFROM openjdk:17-jdk-slim\n\n# Set the working directory\nWORKDIR /app\n\n# Copy the JAR file from the builder stage\nCOPY --from=builder /build/target/myapp.jar /app/myapp.jar\n\n# Expose the application's port\nEXPOSE 8080\n\n# Run the application\nENTRYPOINT [\"java\", \"-jar\", \"myapp.jar\"]\n```\n\n### **4. PHP Application (Laravel) with Optimized Apache Setup**\n\nThis Dockerfile sets up a Laravel application with Apache and includes optimizations for caching dependencies and permissions.\n\n```Dockerfile\n# Base image\nFROM php:8.1-apache\n\n# Enable required PHP extensions and Apache modules\nRUN docker-php-ext-install pdo pdo_mysql \u0026\u0026 a2enmod rewrite\n\n# Set the working directory\nWORKDIR /var/www/html\n\n# Install Composer (dependency manager for PHP)\nCOPY --from=composer:2 /usr/bin/composer /usr/bin/composer\n\n# Copy application code and install dependencies\nCOPY . /var/www/html\nRUN composer install --optimize-autoloader --no-dev\n\n# Set ownership and permissions\nRUN chown -R www-data:www-data /var/www/html \\\n    \u0026\u0026 chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache\n\n# Expose port 80 for Apache\nEXPOSE 80\n\n# Start Apache server\nCMD [\"apache2-foreground\"]\n```\n\n### **5. Multi-container Docker Setup (Docker Compose)**\n\nThis example uses Docker Compose to manage multiple services (Nginx, Node.js, and a PostgreSQL database) within a single setup.\n\n**Dockerfile for Node.js:**\n```Dockerfile\nFROM node:16-alpine\n\nWORKDIR /app\nCOPY package*.json ./\nRUN npm install\nCOPY . .\n\nEXPOSE 3000\nCMD [\"npm\", \"start\"]\n```\n\n**Docker Compose Configuration:**\n```yaml\nversion: '3.8'\n\nservices:\n  nginx:\n    image: nginx:latest\n    ports:\n      - \"80:80\"\n    volumes:\n      - ./nginx.conf:/etc/nginx/nginx.conf\n    depends_on:\n      - nodejs\n\n  nodejs:\n    build: ./node-app\n    ports:\n      - \"3000:3000\"\n    environment:\n      - NODE_ENV=production\n    depends_on:\n      - db\n\n  db:\n    image: postgres:14\n    environment:\n      POSTGRES_USER: user\n      POSTGRES_PASSWORD: password\n      POSTGRES_DB: mydatabase\n    volumes:\n      - db-data:/var/lib/postgresql/data\n\nvolumes:\n  db-data:\n```\n\n### **6. Using Build Arguments and Environment Variables**\n\nThis Dockerfile makes use of build arguments (`ARG`) and environment variables (`ENV`), which allow configuration during build and runtime.\n\n```Dockerfile\n# Base image\nFROM python:3.9-slim\n\n# Build arguments (passed during docker build)\nARG ENVIRONMENT=production\n\n# Environment variables (available during container runtime)\nENV ENVIRONMENT=${ENVIRONMENT}\nENV APP_PORT=5000\n\n# Set the working directory\nWORKDIR /app\n\n# Install dependencies\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Copy application code\nCOPY . .\n\n# Expose the application port\nEXPOSE ${APP_PORT}\n\n# Run the app\nCMD [\"python\", \"app.py\"]\n```\n\nYou can build the image with:\n```bash\ndocker build --build-arg ENVIRONMENT=staging -t my-app .\n```\n\n### **7. Using Health Checks in Dockerfile**\n\nThis Dockerfile adds a health check to ensure that the application inside the container is running and healthy.\n\n```Dockerfile\nFROM node:16-alpine\n\n# Set the working directory\nWORKDIR /app\n\n# Copy and install dependencies\nCOPY package*.json ./\nRUN npm install\n\n# Copy application code\nCOPY . .\n\n# Expose the application port\nEXPOSE 3000\n\n# Add a health check to ensure the app is responding\nHEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \\\n  CMD curl --fail http://localhost:3000 || exit 1\n\n# Start the application\nCMD [\"npm\", \"start\"]\n```\n\n---\n\n### **Best Practices for Advanced Dockerfiles:**\n1. **Use Multi-stage Builds:** Reduces image size by separating build dependencies from runtime dependencies.\n2. **Use Non-root User:** Enhances security by avoiding running containers as root.\n3. **Leverage Caching:** Optimize builds by leveraging Docker’s layer caching mechanism (e.g., copy `requirements.txt` first before copying the rest).\n4. **Health Checks:** Monitor and restart unhealthy containers automatically.\n5. **Use Build Arguments and Environment Variables:** Allow flexible configuration at both build and runtime.\n6. **Minimal Base Images:** Choose lightweight base images (e.g., `alpine`) to reduce image size and attack surface.\n7. **Clean Up:** Remove temporary files, packages, or build tools after installation to keep the final image clean.\n\nThese advanced Dockerfile techniques ensure your containerized applications are more efficient, secure, and production-ready.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatulkamble%2Fdockerfile-examples","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fatulkamble%2Fdockerfile-examples","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fatulkamble%2Fdockerfile-examples/lists"}