Deploy a dnsmasq in LAN with Docker to Accelerate Network Access

This page is also available in: 中文

Public DNS services often impose usage limits on users, resulting in slow loading times or even inability to access certain websites.

To address this issue, you can deploy a dnsmasq cache DNS server on your local network server (or router). This server will cache DNS records for visited websites, allowing for faster IP resolution and speeding up webpage loading times.

dnsmasq is a lightweight network service tool primarily used for providing DNS and DHCP services. It is commonly used in small network environments such as home networks or small offices.

Assuming your local network server (192.168.1.8) already has Docker installed, you can use the following Docker Compose configuration file to start the dnsmasq container.

services:
  dnsmasq:
    image: dockurr/dnsmasq
    container_name: dnsmasq
    environment:
      DNS1: "114.114.114.114"
      DNS2: "8.8.8.8"
    ports:
      - 53:53/udp
      - 53:53/tcp
    cap_add:
      - NET_ADMIN

In the above configuration, DNS1 and DNS2 are the upstream DNS servers, which can be modified according to your needs.

# Create the container
sudo docker compose up -d

If no errors are reported, the dnsmasq container has been successfully deployed. You can also use the following command to check the container status:

# Make sure to execute the command in the directory where the docker-compose.yml file is located
sudo docker compose logs -f

Resolving Port 53 Conflict

For Linux servers such as Ubuntu Server, the port 53 may already be occupied by the systemd-resolved service. To resolve this conflict, you need to disable the service and create a new /etc/resolve.conf file with the nameserver pointing to 127.0.0.1.

# Disable the systemd-resolved service
sudo systemctl disable systemd-resolved
# Stop the service
sudo systemctl stop systemd-resolved
# Backup the resolve.conf file
sudo mv /etc/resolve.conf /etc/resolve.bak
# Create a new resolve.conf file
echo "nameserver 127.0.0.1" | sudo tee /etc/resolv.conf

Using the dnsmasq Server

Once dnsmasq is deployed, you can modify the DNS settings on your router to point to the IP address of your local network server. For example:

This way, all devices connected to this router will automatically use dnsmasq for DNS resolution.

Although the initial access to uncached websites may still experience slow resolution, subsequent visits will be much faster once dnsmasq completes the initial resolution.

This article was published on 2024-08-17 and last updated on 2024-09-23.

This article is copyrighted by torchtree.com and unauthorized reproduction is prohibited.