Built script to install a docker dns free with bind9

Give the Script Execute Permissions:

Open your terminal and run the following command to give execute permissions to the script:

chmod +x install-dns.sh

Run the Script:

Now, you can run the script with:

./install-dns.sh


#!/bin/bash

Set variables

DOCKER_IMAGE_NAME=“my-dns-server”
DOCKER_CONTAINER_NAME=“dns-server”
ZONE_FILE=“db.example.com

Install required packages

echo “Updating system and installing Docker…”
sudo apt update && sudo apt install -y docker.io

Check if Docker is installed

if ! command -v docker &> /dev/null; then
echo “Docker installation failed. Exiting.”
exit 1
fi

Create a directory for the DNS server setup

echo “Creating directory for DNS server setup…”
mkdir -p ./my-dns-server
cd ./my-dns-server

Create Dockerfile

echo “Creating Dockerfile…”
cat > Dockerfile <<EOL

Use the official Ubuntu image as the base image

FROM ubuntu:latest

Install necessary packages (including bind9 for DNS server)

RUN apt update && apt install -y bind9

Copy your BIND configuration files into the container

COPY named.conf /etc/bind/
COPY named.conf.local /etc/bind/

Expose port 53 for DNS traffic (both UDP and TCP)

EXPOSE 53/udp
EXPOSE 53/tcp

Start BIND9 in the foreground using your custom configuration

CMD [“named”, “-f”, “/etc/bind/named.conf”]
EOL

Create named.conf

echo “Creating named.conf…”
cat > named.conf <<EOL
options {
directory “/var/cache/bind”;

// Allow queries from any IP (you may want to restrict this in a real environment)
allow-query { any; };

// Specify the location of your log files
logging {
    channel default_file {
        file "/var/log/named.log" versions 3 size 5m;
        severity info;
        print-time yes;
        print-severity yes;
        print-category yes;
    };
    category default { default_file; };
};

// Allow recursive queries from localhost
allow-recursion { localhost; };

};

// Load additional configurations
include “/etc/bind/named.conf.local”;
EOL

Create named.conf.local

echo “Creating named.conf.local…”
cat > named.conf.local <<EOL
zone “example.com” {
type master;
file “/etc/bind/db.example.com”; # You’ll need to create this file as well
};
EOL

Create db.example.com (zone file)

echo “Creating db.example.com…”
cat > $ZONE_FILE <<EOL
$TTL 86400
@ IN SOA ns1.example.com. admin.example.com. (
2025022401 ; Serial
3600 ; Refresh
1800 ; Retry
1209600 ; Expire
86400 ) ; Minimum TTL

    IN      NS      ns1.example.com.

ns1 IN A 192.168.1.1
@ IN A 192.168.1.1
EOL

Build the Docker image

echo “Building Docker image…”
sudo docker build -t $DOCKER_IMAGE_NAME .

Run the Docker container

echo “Running Docker container…”
sudo docker run -d -p 53:53/udp -p 53:53/tcp --name $DOCKER_CONTAINER_NAME $DOCKER_IMAGE_NAME

Confirm that the container is running

echo “Checking if the container is running…”
sudo docker ps

Final message

echo “DNS server setup complete! You can now query the server using ‘dig @localhost example.com’.”