How to set dns in docker compose

Setting DNS in Docker Compose

Running services in Docker containers comes with its fair share of challenges, one of which is configuring DNS settings. In this article, we will explore how to set DNS in Docker Compose to ensure smooth functioning of your containers.

When you spin up a container in Docker, it is isolated from the host machine and may have its own networking requirements. By default, containers use the DNS settings of the host machine which may not always be ideal. Docker Compose allows you to override these settings and specify custom DNS servers for your containers.

Step 1: Create a Docker Compose File

The first step is to create a Docker Compose file for your project. This file will define the services, networks, and volumes needed to run your application. Open a text editor and create a new file named docker-compose.yml.

Inside the file, define your services as usual. For example:

version: '3.7'
services:
   web:
     image: nginx:latest
     ports:
       - "8080:80"

Step 2: Add DNS Configuration

To set custom DNS servers for your containers, you need to add a dns key under the service definition in your Docker Compose file. For example:

version: '3.7'
services:
   web:
     image: nginx:latest
     ports:
       - "8080:80"
     dns:
       - 8.8.8.8
       - 8.8.4.4

In this example, we have added Google’s public DNS servers (8.8.8.8 and 8.8.4.4) to the dns key for the web service.

Step 3: Restart Your Containers

After adding the DNS configuration to your Docker Compose file, you need to restart your containers for the changes to take effect. Run the following command in your terminal:

docker-compose down
docker-compose up -d

Once your containers are restarted, they will use the custom DNS settings specified in the Docker Compose file. You can verify this by inspecting the container’s networking configuration.

Setting DNS in Docker Compose is a simple yet powerful way to customize the networking settings of your containers. By specifying custom DNS servers, you can ensure that your containers have reliable and secure connectivity.

Remember to test your configuration thoroughly to ensure that it meets your application’s requirements. Happy coding!

Comments