Authenticating Azure Service Bus in a Local Docker Container Using Azure CLIChris Child | 2024-09-10 | 2 min read| Comments
When running services locally in Docker that need to authenticate with Azure Service Bus, you can leverage the Azure CLI (az login
) to provide credentials. This avoids manually setting up connection strings or managed identities for local development.
Step 1: Authenticate Using Azure CLI
Run the following command to authenticate and persist credentials inside a volume:
docker run -it --rm -v "$PWD/azure-auth:/root/.azure" mcr.microsoft.com/azure-cli az login
This will:
- Prompt you to log in to Azure.
- Store authentication tokens in a directory called
azure-auth
inside your project. - Remove the container after login (
--rm
ensures it doesn’t persist).
Step 2: Mount the Credentials in Your Service Container
Modify your docker-compose.yml
to mount this volume in the service that needs Azure authentication:
services:
my-service:
image: my-service-image
volumes:
- "./azure-auth:/root/.azure"
This ensures that when your service runs, it has access to the Azure credentials stored in azure-auth
.
Step 3: Verify Authentication
Inside the running container, you can verify that authentication works by running:
az account show
If configured correctly, this should display your logged-in Azure account details.
This setup allows your Docker container to seamlessly authenticate with Azure Service Bus while keeping credentials isolated and manageable.
Step 4: Use in C# to Connect to Azure Service Bus
Once authentication is set up, you can use the Azure SDK for .NET to connect to Azure Service Bus in your C# application. Ensure your application runs inside the container with the mounted credentials.
Install the required NuGet package if you haven't already:
Then, in your C# application, use DefaultAzureCredential
to authenticate and connect to Service Bus:
This setup allows your C# application to authenticate with Azure Service Bus using the credentials stored in the mounted azure-auth directory. 🚀