Skip to content
SHOPAII

Detailed Tutorial for Installing imgproxy with Docker

Docker · Published · 15 min read

Detailed Tutorial for Installing imgproxy with Docker

  1. Tutorial Outline

  2. What is imgproxy

  3. Steps to Install imgproxy with Docker

  4. Enable imgproxy Unsigned Mode

  5. Configure imgproxy Caching

  6. Restrict Source Domains (Security Configuration)

  7. WebP Conversion URL Format Explanation

  8. Verification and Common Issues

  9. Advanced Guide: Nginx + imgproxy for CDN Acceleration and Automatic WebP Conversion

  10. What is imgproxy

imgproxy is a high-performance, lightweight image processing service designed specifically for web scenarios. It can remotely fetch images via URL parameters and real-time perform operations such as resizing, cropping, format conversion (e.g., JPG to WebP), and compression, ultimately returning the processed image.

Core Features:

  • Developed based on Go, offering exceptional performance and low memory footprint

  • Supports mainstream image formats (JPG, PNG, WebP, AVIF, etc.)

  • Supports various image processing operations including cropping, resizing, rotation, watermarking, and compression

  • Built-in security mechanisms (signature verification, source domain restriction) to prevent malicious URL attacks

  • Supports caching to significantly improve response speed for repeated requests

  • Can be quickly deployed via Docker without complex environment configuration

imgproxy is commonly used in e-commerce, content platforms, and other scenarios requiring extensive image processing, effectively reducing image size and improving page loading speed.

  1. How to Install imgproxy with Docker

Prerequisites

  • Docker and Docker Compose installed (Compose is recommended for easier management)

  • Network access permission on the server/local environment

  • At least 100MB of available disk space

Installation Steps

Method 1: Single Docker Command (Quick Test)

Pull the official imgproxy image (latest stable version)

docker pull darthsim/imgproxy:latest

Start the container (basic configuration, for testing only)

docker run -d \ –name imgproxy \ -p 8080:8080 \ darthsim/imgproxy:latest

Method 2: Docker Compose (Recommended for Production)

  1. Create a docker-compose.yml file: version: ‘3.8’

services: imgproxy: image: darthsim/imgproxy:latest container_name: imgproxy restart: always # Auto-restart if the container exits unexpectedly ports: – “8080:8080” # Port mapping: host 8080 -> container 8080 environment: # Basic configuration (to be extended later) – IMGPROXY_PORT=8080 – IMGPROXY_HOST=0.0.0.0 volumes: # Mount cache directory (for caching configuration later) – ./imgproxy_cache:/var/cache/imgproxy networks: – imgproxy_network

networks: imgproxy_network: driver: bridge

  1. Start the container:# Create cache directory (to avoid permission issues) mkdir -p ./imgproxy_cache && chmod 777 ./imgproxy_cache

Start the container

docker-compose up -d

  1. Verify installation: Visit http://YourIP:8080/health. If it returns OK, imgproxy has started successfully.

  2. How to Enable Unsigned Mode

imgproxy enables signature verification by default (to prevent malicious URL construction). However, in development/test environments or internal use, you can enable unsigned mode to simplify URL construction.

Enable Steps

  1. Modify docker-compose.yml and add environment variables for unsigned mode: version: ‘3.8’

services: imgproxy: image: darthsim/imgproxy:latest container_name: imgproxy restart: always ports: – “8080:8080” environment: – IMGPROXY_PORT=8080 – IMGPROXY_HOST=0.0.0.0 # Enable unsigned mode (core configuration) – IMGPROXY_DISABLE_SIGNATURE=true # Optional: Allow unsigned URLs (compatible with older versions) – IMGPROXY_ALLOW_UNSAFE_URL=true volumes: – ./imgproxy_cache:/var/cache/imgproxy networks: – imgproxy_network

networks: imgproxy_network: driver: bridge

  1. Restart the container: docker-compose down && docker-compose up -d

Verify Unsigned Mode

Test with a simple image processing URL: http://YourIP:8080/rs:fit:300:300/plain/https://picsum.photos/800/800

  • rs:fit:300:300: Resize adaptively to 300×300

  • plain: Indicates unsigned (unsigned mode identifier)

  • https://picsum.photos/800/800: Original image URL

If it returns a 300×300 image normally, unsigned mode is enabled successfully.

  1. How to Configure Caching

imgproxy supports multiple caching methods (local file, Redis, S3, etc.). Here, we recommend local file caching (simplest, suitable for small to medium-scale use).

Configuration Steps

  1. Modify docker-compose.yml and add environment variables for caching: version: ‘3.8’

services: imgproxy: image: darthsim/imgproxy:latest container_name: imgproxy restart: always ports: – “8080:8080” environment: – IMGPROXY_PORT=8080 – IMGPROXY_HOST=0.0.0.0 # Unsigned mode configuration – IMGPROXY_DISABLE_SIGNATURE=true – IMGPROXY_ALLOW_UNSAFE_URL=true # Core caching configuration – IMGPROXY_CACHE_TYPE=file # Cache type: local file – IMGPROXY_CACHE_PATH=/var/cache/imgproxy # Cache directory (corresponds to mounted volume) – IMGPROXY_CACHE_TTL=86400 # Cache validity period (seconds), set to 1 day here – IMGPROXY_CACHE_SIZE=10GB # Maximum cache space (adjust as needed) – IMGPROXY_CACHE_CLEANUP_INTERVAL=3600 # Cache cleanup interval (seconds), clean up expired cache every 1 hour volumes: – ./imgproxy_cache:/var/cache/imgproxy # Mount cache directory to host networks: – imgproxy_network

networks: imgproxy_network: driver: bridge

  1. Restart the container: docker-compose down && docker-compose up -d

  2. Verify caching:

  3. When accessing the image processing URL for the first time, cache files will be generated in the ./imgproxy_cache directory;

  4. Accessing the same URL again will have significantly improved response speed (reading directly from cache);

  5. You can check the cache directory size with du -sh ./imgproxy_cache to confirm caching is working.

Cache Parameter Explanation

Parameter

Description

Example Value

IMGPROXY_CACHE_TYPE

Cache type

file (local file)/redis (Redis)/s3 (S3)

IMGPROXY_CACHE_TTL

Cache validity period

86400 (1 day), 604800 (7 days)

IMGPROXY_CACHE_SIZE

Maximum cache capacity

10GB, 500MB

IMGPROXY_CACHE_CLEANUP_INTERVAL

Cache cleanup interval

3600 (1 hour)

  1. How to Restrict Source Domains (Security Configuration)

To prevent imgproxy from being abused to process images from arbitrary third-party domains (consuming server resources and posing security risks), it is recommended to restrict allowed source domains in production environments, only opening legitimate domains required for business.

Restriction Method (Whitelist Configuration)

imgproxy provides environment variables to implement source domain whitelisting, supporting exact matching and wildcard matching for flexible configuration based on needs.

Configuration Steps

  1. Modify docker-compose.yml and add environment variables for source domain restriction (integrate with existing configuration): version: ‘3.8’

services: imgproxy: image: darthsim/imgproxy:latest container_name: imgproxy restart: always ports: – “8080:8080” environment: – IMGPROXY_PORT=8080 – IMGPROXY_HOST=0.0.0.0 # Unsigned mode configuration – IMGPROXY_DISABLE_SIGNATURE=true – IMGPROXY_ALLOW_UNSAFE_URL=true # Caching configuration – IMGPROXY_CACHE_TYPE=file – IMGPROXY_CACHE_PATH=/var/cache/imgproxy – IMGPROXY_CACHE_TTL=86400 – IMGPROXY_CACHE_SIZE=10GB – IMGPROXY_CACHE_CLEANUP_INTERVAL=3600 # Source domain restriction (core configuration, update to target origin) – IMGPROXY_ALLOWED_SOURCES=shopaii.net,*.shopaii.net # Whitelisted domains, separated by commas # Optional: Disable IP as source domain (enhance security further) – IMGPROXY_DISALLOW_IP_SOURCES=true volumes: – ./imgproxy_cache:/var/cache/imgproxy networks: – imgproxy_network

networks: imgproxy_network: driver: bridge

  1. Key parameter explanation:

  2. IMGPROXY_ALLOWED_SOURCES: Whitelist of allowed source domains, supporting two formats:

    • Exact match: e.g., shopaii.net, only allows processing images from this domain;

    • Wildcard match: e.g., *.shopaii.net, allows processing images from all subdomains of shopaii.net (e.g., static.shopaii.net).

  3. IMGPROXY_DISALLOW_IP_SOURCES=true: Prohibits using IP addresses as source domains, preventing bypassing domain restrictions via IP. Recommended to enable.

  4. Restart the container to apply the configuration: docker-compose down && docker-compose up -d

Verify Restriction Effect

  1. Test whitelisted domain: Visit http://YourIP:8080/format:webp/plain/https://shopaii.net/img.jpg (replace with a real image URL in the whitelist). If it returns the processed image normally, the configuration is effective.

  2. Test non-whitelisted domain: Visit http://YourIP:8080/format:webp/plain/https://other.com/img.jpg (non-whitelisted domain). It should return a 403 Forbidden error, indicating the restriction is working.

Advanced Configuration (Complex Scenarios)

For more granular control (e.g., allowing specific ports or paths), you can use regular expression matching by adding the following parameters:

Enable regular expression matching for source domains

  • IMGPROXY_ALLOWED_SOURCES_REGEX=true

Regular expression rule (example: allow all paths under shopaii.net and its subdomains, with ports 80/443)

  • IMGPROXY_ALLOWED_SOURCES=^https?://(.+.)?shopaii.net(:80|:443)?/.*$

Note: Regular expressions must be strictly verified to avoid security risks due to rule omissions.

  1. WebP Conversion URL Explanation

imgproxy supports converting any image to WebP format (smaller size, faster loading), with the core being specifying the target format via the format parameter in the URL.

WebP Conversion URL Format

Basic format: http://imgproxyAddress/[processingParameters]/format:webp/plain/[originalImageURL]

Core Parameter Explanation

  • format:webp: Specify output format as WebP (required);

  • Optional parameter: quality:[value] (set WebP quality, 1-100, default 80).

Examples

  1. Basic conversion (default quality): http://YourIP:8080/format:webp/plain/https://shopaii.net/logo.jpg

  2. Resize + WebP conversion (quality 90): http://YourIP:8080/rs:fit:400:400/quality:90/format:webp/plain/https://shopaii.net/banner.jpg

  3. Crop + WebP conversion: http://YourIP:8080/rs:crop:200:200:100:100/format:webp/plain/https://shopaii.net/product.jpg (rs:crop:width:height:X:Y: Crop a 200×200 area from position X=100, Y=100 of the original image)

Notes

  • The original image URL must be encoded if it contains special characters such as & or ?. Example:

  • Original URL: https://shopaii.net/img.jpg?width=800&height=600

  • Encoded URL: https%3A%2F%2Fshopaii.net%2Fimg.jpg%3Fwidth%3D800%26height%3D600

  • Final conversion URL: http://YourIP:8080/format:webp/plain/https%3A%2F%2Fshopaii.net%2Fimg.jpg%3Fwidth%3D800%26height%3D600

  • Higher WebP quality results in larger file sizes. It is recommended to adjust based on business needs (70-90 is optimal).

  • Verification and Common Issues

Overall Verification Process

After completing all configurations, verify full functionality as follows:

  1. Visit the health check endpoint: http://YourIP:8080/health, confirm it returns OK;

  2. Test unsigned URL access with images from whitelisted domains, confirm images are processed normally;

  3. Access the same URL repeatedly, check if cache files are generated in the cache directory to confirm caching works;

  4. Test WebP conversion URL, confirm the returned format is WebP;

  5. Access images from non-whitelisted domains, confirm a 403 error is returned to verify source domain restriction works.

Troubleshooting Common Issues

  • Container fails to start: Check if the port is occupied (use an unused port) and if the cache directory has correct permissions (ensure 777 permissions);

  • Image fails to load (403 error): Confirm the source domain is in the whitelist. If signature verification is enabled, check if the URL signature is correct;

  • Caching not working: Verify IMGPROXY_CACHE_PATH matches the mounted directory and the container has write permission to the cache directory;

  • WebP conversion fails: Confirm the original image format supports conversion and the URL is encoded correctly.

  • Advanced Guide: Nginx + imgproxy for CDN Acceleration and Automatic WebP Conversion

For business scenarios, using Nginx reverse proxy with imgproxy enables the CDN acceleration domain (cdn.shopaii.net) to provide external services, while achieving the core requirement of automatic WebP conversion for JPG/PNG and direct mirroring for other files, balancing access speed, bandwidth optimization, and business compatibility. Core logic: Nginx distributes requests by file type, forwards JPG/PNG to imgproxy for conversion, directly reverse proxies non-image files to the origin server, and optimizes responses via Nginx caching to form a complete acceleration chain.

Prerequisites

  • Completed imgproxy configuration as described earlier (including source domain restriction: allowing shopaii.net and its subdomains);

  • Nginx installed on the server with domain resolution permission (resolve cdn.shopaii.net to the server IP);

  • SSL certificate applied (Let’s Encrypt recommended) to enable HTTPS access (essential for CDN scenarios).

Core Configuration Steps

Step 1: Confirm imgproxy Source Domain Restriction Configuration

Ensure the source domain whitelist in docker-compose.yml is configured for shopaii.net and its subdomains (updated earlier). No additional adjustments are needed; just ensure the container is restarted and running normally.

Step 2: Nginx Configuration (cdn.shopaii.net Domain)

Create a cdn.shopaii.net.conf file in the Nginx configuration directory (usually /etc/nginx/conf.d/). Distribute requests by file extension via location blocks to handle images and non-image files separately. The complete configuration is as follows:

server { listen 80; server_name cdn.shopaii.net; # Force redirect to HTTPS return 301 https://$host$request_uri; }

server { listen 443 ssl http2; server_name cdn.shopaii.net;

# SSL certificate configuration (replace with actual certificate path)
ssl_certificate /etc/nginx/ssl/cdn.shopaii.net/fullchain.pem;
ssl_certificate_key /etc/nginx/ssl/cdn.shopaii.net/privkey.pem;
# SSL optimization configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# Client caching configuration (cache static resources for 7 days, adjust non-image cache policy as needed)
expires 7d;
add_header Cache-Control "public, max-age=604800";

# Nginx local caching configuration (cache WebP images processed by imgproxy and non-image files from origin)
proxy_cache_path /var/nginx/cache/cdn levels=1:2 keys_zone=cdn_cache:100m inactive=7d max_size=10G;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 304 7d;
proxy_cache_valid any 1m;
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
add_header X-Proxy-Cache $upstream_cache_status; # For debugging cache status (HIT/MISS/EXPIRED)

# Core: Forward JPG/PNG images to imgproxy for automatic WebP conversion
location ~* \.(jpg|jpeg|png)$ {
    # Forward to local imgproxy service, append WebP conversion parameters (quality 85, balancing clarity and size)
    proxy_pass http://127.0.0.1:8080/format:webp/quality:85/plain/https://shopaii.net$request_uri;
    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;

    # Handle special case: Auto-fall back to original image if client does not support WebP (optional optimization)
    if ($http_accept !~* "image/webp") {
        proxy_pass https://shopaii.net$request_uri;
    }
}

# Directly reverse proxy other files (e.g., JS, CSS, GIF, videos) to origin without passing through imgproxy
location / {
    proxy_pass https://shopaii.net$request_uri;
    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;

    # Disable caching for 404/500 error pages
    proxy_cache_bypass $http_range $http_if_range;
    proxy_no_cache $http_range $http_if_range;
}

# Health check endpoint (exposed externally for monitoring)
location /health {
    proxy_pass http://127.0.0.1:8080/health;
    proxy_set_header Host $host;
    expires -1; # Do not cache health check results
    add_header Cache-Control "no-store, no-cache, must-revalidate";
}

# Deny access to sensitive paths
location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
}

}

Step 3: Create Nginx Cache Directory and Authorize

Execute the following commands to create the cache directory and avoid permission issues causing cache failure:

mkdir -p /var/nginx/cache/cdn chown -R nginx:nginx /var/nginx/cache chmod -R 755 /var/nginx/cache

Step 4: Verify Nginx Configuration and Restart

Check if configuration syntax is correct

nginx -t

Restart Nginx to apply the configuration

systemctl restart nginx

Core Logic Explanation

  1. Request Distribution Logic:

  2. When a user accesses https://cdn.shopaii.net/img/product.jpg (JPG format), Nginx matches the ~* .(jpg|jpeg|png)$ rule, forwards it to imgproxy for WebP conversion, and returns the result;

  3. When a user accesses https://cdn.shopaii.net/js/main.js (JS file), Nginx matches the general / rule, directly reverse proxies to the origin https://shopaii.net/js/main.js to achieve mirroring.

  4. Compatibility Optimization: The configuration includes a check for client WebP support. If the client (e.g., older browsers) does not support WebP, it automatically falls back to the original image from the origin to avoid compatibility issues.

  5. Dual Caching Optimization: imgproxy caches image processing logic, and Nginx caches final response results (WebP images, non-image files). This dual caching reduces repeated processing and origin requests, improving CDN acceleration effectiveness.

  6. Origin Isolation: Users only access resources via the CDN domain (cdn.shopaii.net). The origin domain (shopaii.net) does not directly expose static resource services, enhancing security and access control capabilities.

Verification and Debugging

  1. WebP Conversion Verification: Visit https://cdn.shopaii.net/img/logo.jpg and check the response header via browser developer tools:

  2. Content-Type is image/webp, indicating successful conversion;

  3. X-Proxy-Cache is HIT (cache hit) or MISS (first access), indicating Nginx caching is working.

  4. Non-Image File Mirroring Verification: Visit https://cdn.shopaii.net/css/style.css and confirm the response content is consistent with the origin https://shopaii.net/css/style.css, indicating normal mirroring.

  5. Compatibility Verification: Access a JPG image using a browser that does not support WebP. It should return the original image format (Content-Type: image/jpeg), indicating the fallback logic works.

Advanced Optimization Suggestions

  • CDN Overlay: Integrate cdn.shopaii.net with public CDNs such as Alibaba Cloud or Tencent Cloud to further improve cross-region access speed, with Nginx as the origin node.

  • Image Quality Grading: Distinguish image types by path via Nginx location blocks and configure different WebP qualities. For example, 90 for product images and 75 for thumbnails. Example: location ~ /img/product/..(jpg|jpeg|png)$ { proxy_pass http://127.0.0.1:8080/format:webp/quality:90/plain/https://shopaii.net$request_uri; } location ~ /img/thumb/..(jpg|jpeg|png)$ { proxy_pass http://127.0.0.1:8080/format:webp/quality:75/plain/https://shopaii.net$request_uri; }

  • Monitoring and Alerting: Monitor imgproxy processing volume, Nginx cache hit rate, and request proportion of various file types via Prometheus + Grafana. Set up abnormal alerts (e.g., alert when cache hit rate is below 70%).

  • Automatic Certificate Renewal: Use Certbot to configure automatic SSL certificate renewal to avoid HTTPS service interruption. Command example: certbot –nginx -d cdn.shopaii.net –agree-tos –email [email protected].

Summary

  1. imgproxy is a high-performance image processing service. Combined with source domain restrictions, it meets production environment security requirements. When used with Nginx, it enables more flexible resource distribution strategies;

  2. Docker Compose is the preferred method for installing imgproxy. Core configurations must cover unsigned mode, caching, and source domain restrictions to ensure stability and security;

  3. The Nginx + imgproxy combination enables refined management of CDN acceleration domains, achieving automatic WebP conversion for JPG/PNG and mirroring for other files via file type matching, balancing performance and compatibility;

  4. Dual caching (imgproxy cache + Nginx cache) and SSL optimization are essential for production environments, significantly improving access speed and service stability.