HTTP Basic Authentication offers a quick way to secure access to internal or staging services in a Docker environment, especially for controlled scenarios where high security isn’t critical. Although credentials sent via Basic Authentication can be decoded if intercepted, combining it with HTTPS ensures encryption, making it suitable for simple use cases. Here, we’ll set up Caddy as a reverse proxy with Basic Authentication to limit access to a service running in another container.
Scenario Overview
In this example, we have:
- A Caddy container named
caddy
- A service container named
sampledockercontainer
, which is the service we’re protecting, running on port8080
- Both containers are on the same Docker network
- The goal is to limit access to the
sampledockercontainer
service with Basic Authentication
Setting Up the Caddyfile
Start with a simple Caddyfile that proxies traffic to the sampledockercontainer
:
example.com {
reverse_proxy sampledockercontainer:8080
}
This configuration forwards all requests for example.com
to the sampledockercontainer
service within the Docker network.
Generating a Hashed Password for Authentication
Since Caddy is running as a Docker container, use the following docker exec
command to generate a hashed password for authentication:
docker exec -it caddy caddy hash-password --plaintext 'yoursupersecretpassword'
Assuming your username is user
, the command returns a hashed password like:
$2a$14$UnmpufOS3hIBsW5Jn.lbpe0qtoa5kCKYfJNPGsgnOr2D6mPma8aPm
Adding Basic Authentication to the Caddyfile
Update the Caddyfile to include Basic Authentication, securing access to example.com
:
example.com {
basicauth {
user $2a$14$UnmpufOS3hIBsW5Jn.lbpe0qtoa5kCKYfJNPGsgnOr2D6mPma8aPm
}
reverse_proxy sampledockercontainer:8080
}
Now, visitors will be prompted for a username and password before gaining access.
Restricting Authentication to Specific Paths
You may want only certain paths to require authentication, allowing general access to others. For example, you can limit Basic Authentication to the /admin
path while keeping the root URL publicly accessible:
example.com {
basicauth /admin/* {
user $2a$14$UnmpufOS3hIBsW5Jn.lbpe0qtoa5kCKYfJNPGsgnOr2D6mPma8aPm
}
reverse_proxy /admin/* sampledockercontainer:8080
reverse_proxy /* sampledockercontainer:8080
}
With this setup:
- Requests to
example.com
are open to all users. - Requests to
example.com/admin/
require a valid username and password.
Conclusion
This Caddyfile setup demonstrates a simple, effective way to protect containerized services with Basic Authentication. For Dockerized applications, Caddy makes it easy to limit access to sensitive areas, securing your internal or staging environments with minimal configuration.