Caddy Configuration for Django in Docker
This guide demonstrates how to configure Caddy as a reverse proxy for a Django application running in a Docker container. Below is a sample configuration that works well when accessed via a domain name.
Basic Caddyfile Setup
mydomain.com {
reverse_proxy django:5000 {
header_upstream Host {host}
header_upstream X-Real-IP {remote}
header_upstream X-Forwarded-Proto {scheme}
header_upstream X-CSRFToken {~csrftoken}
}
log stdout
errors stdout
gzip
}
Explanation of the Configuration
mydomain.com: This is the domain name through which your application will be accessed.reverse_proxy: This directive forwards incoming requests to the specified backend service (in this case, the Django application running on port 5000).header_upstream: These lines set various headers that are forwarded to the upstream service, which can be useful for logging and security purposes.log stdoutanderrors stdout: These options direct Caddy to log requests and errors to standard output, which is helpful for debugging.gzip: This enables gzip compression for responses, improving load times.
Accessing via IP Address
While the configuration above works perfectly with the domain name, accessing the server directly via its IP address (e.g., http://156.130.11.8) may lead to a 404 error:
404 Site 156.130.11.8 is not served on this interface
Troubleshooting IP Access
To resolve this issue, you need to ensure that your Caddyfile can also handle requests made directly to the server's IP address. You can achieve this by adding a catch-all configuration:
* {
reverse_proxy django:5000 {
header_upstream Host {host}
header_upstream X-Real-IP {remote}
header_upstream X-Forwarded-Proto {scheme}
header_upstream X-CSRFToken {~csrftoken}
}
log stdout
errors stdout
gzip
}
Important Notes
- The
*in the configuration above acts as a wildcard, allowing Caddy to serve requests made to any hostname, including the server's IP address. - Ensure that your Docker container is properly configured to allow connections on the specified port.
Conclusion
With this configuration, you should be able to access your Django application both via its domain name and directly through its IP address. For further details, refer to the Caddy documentation.