One place for hosting & domains

      HAProxy Network Error: cannot bind socket



      Part of the Series:
      Common HAProxy Errors

      This tutorial series explains how to troubleshoot and fix some of the most common errors that you may encounter when using the HAProxy TCP and HTTP proxy server.

      Each tutorial in this series includes descriptions of common HAProxy configuration, network, filesystem, or permission errors. The series begins with an overview of the commands and log files that you can use to troubleshoot HAProxy. Subsequent tutorials examine specific errors in detail.

      Introduction

      An HAProxy cannot bind socket error message is generated when there is another process listening on the same interface and TCP port combination that HAProxy is configured to use, or when HAProxy attempts to use an IP address that is not assigned to a network interface. Both error conditions derive from the underlying operating system’s network stack.

      In the first case, when there is another process that is already using an interface and port that HAProxy is attempting to bind to, the underlying error on Linux is EADDRINUSE. The issue is that only a single process can be bound to an IP address and port combination at any given time.

      In the second case, when HAProxy is attempting to use an IP address that is not assigned to an interface on the system, the underlying error on Linux is EADDRNOTAVAIL. The issue here is that an IP socket cannot be created using an address that is not available to the operating system.

      However, both underlying errors generate the same HAProxy error message, so troubleshooting a cannot bind socket error requires examining the list of currently used sockets and IP addresses on a Linx system.

      To detect a cannot bind socket error message, you will need to examine systemctl and journalctl output to determine the IP address and port combination that are causing the error. Then you can inspect other running processes and network interfaces and decide how to resolve the issue, whether it is by switching servers, changing the IP address or port that HAProxy uses, or any combination of these options.

      Troubleshooting with systemctl

      Following the troubleshooting steps from the How to Troubleshoot Common HAProxy Errors tutorial at the beginning of this series, the first step when you are troubleshooting an cannot bind socket error message is to check HAProxy’s status with systemctl.

      The output from systemctl status will in many cases contain all the diagnostic information that you need to resolve the error. It may include the IP address that HAProxy is using, as well as the port that it is attempting to bind to. The output will also indicate how long HAProxy has been unable to start so that you can determine how long the issue has been affecting HAProxy.

      Note: If you are using Ubuntu or a Debian-derived Linux distribution, systemctl does not include output from HAProxy with a cannot bind socket error message that describes the problem. Skip to the the next section of this tutorial, Troubleshooting Using journalctl Logs to learn how to examine the systemd logs to find the conflicting IP address or port.

      On CentOS, Fedora and RedHat-derived systems, use this systemctl command to examine HAProxy’s status:

      CentOS and Fedora Systems

      • sudo systemctl status haproxy.service -l --no-pager

      The -l flag will ensure that systemctl outputs the entire contents of a line, instead of substituting in ellipses () for long lines. The --no-pager flag will output the entire log to your screen without invoking a tool like less that only shows a screen of content at a time.

      Since you are troubleshooting a cannot bind socket error message, you should receive output that is similar to the following:

      Output

      ● haproxy.service - HAProxy Load Balancer Loaded: loaded (/usr/lib/systemd/system/haproxy.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Wed 2020-08-19 14:57:05 UTC; 3s ago Process: 138738 ExecStart=/usr/sbin/haproxy -Ws -f $CONFIG -p $PIDFILE (code=exited, status=1/FAILURE) Process: 138736 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -c -q (code=exited, status=0/SUCCESS) Main PID: 138738 (code=exited, status=1/FAILURE) Aug 19 14:57:05 92214d8ff5e2 systemd[1]: Starting HAProxy Load Balancer... Aug 19 14:57:05 92214d8ff5e2 haproxy[138738]: [ALERT] 231/145705 (138738) : Starting frontend main: cannot bind socket [0.0.0.0:80] . . . Aug 19 14:57:05 92214d8ff5e2 systemd[1]: Failed to start HAProxy Load Balancer.

      This example systemctl output includes some highlighted lines from the systemd journal that describes the error. These lines give you all the information about the error that you need to troubleshoot it further. Specifically, the line cannot bind socket [0.0.0.0:80] describes the socket that HAProxy is trying to use (0.0.0.0:80), so you can skip the following journalctl steps and instead proceed to the Troubleshooting with ss and ps Utilities section at the end of this tutorial. The other highlighted line indicates the status of the HAProxy process, which in the case of a cannot bind socket error will show Failed to start HAProxy Load Balancer.

      If your systemctl output does not give specific information about the IP address and port or ports that are causing the error (if you are using Ubuntu or Debian then this applies), then you will need to examine journalctl output from the systemd logs. The following section explains how to use journalctl to troubleshoot a cannot bind socket error.

      Troubleshooting Using journalctl Logs

      If your systemctl output does not include specifics about a cannot bind socket error, you should proceed with using the journalctl command to examine systemd logs for HAProxy.

      On Ubuntu and Debian-derived systems, run the following command:

      • sudo journalctl -u haproxy.service --since today --no-pager

      On CentOS, Fedora, and RedHat-derived systems, use this command to inspect the logs:

      • sudo journalctl -u haproxy.service --since today --no-pager

      The --since today flag will limit the output of the command to log entries beginning at 00:00:00 of the current day only. Using this option will help restrict the volume of log entries that you need to examine when checking for errors.

      If HAProxy is unable to bind to a port that is in use, search through the output for lines that are similar to the following log entries, specifically lines that contain the cannot bind socket error message as highlighted in this example:

      Output

      -- Logs begin at Wed 2020-08-19 19:38:12 UTC, end at Wed 2020-08-19 19:53:53 UTC. -- . . . Aug 19 19:39:21 92214d8ff5e2 systemd[1]: Starting HAProxy Load Balancer... Aug 19 19:39:21 92214d8ff5e2 haproxy[135]: [ALERT] 231/193921 (135) : Starting frontend main: cannot bind socket [0.0.0.0:80] Aug 19 19:39:21 92214d8ff5e2 haproxy[135]: [ALERT] 231/193921 (135) : Starting frontend main: cannot bind socket [:::80] Aug 19 19:39:21 92214d8ff5e2 systemd[1]: haproxy.service: Main process exited, code=exited, status=1/FAILURE Aug 19 19:39:21 92214d8ff5e2 systemd[1]: haproxy.service: Failed with result 'exit-code'. Aug 19 19:39:21 92214d8ff5e2 systemd[1]: Failed to start HAProxy Load Balancer. . . .

      The first highlighted line of output indicates that HAProxy cannot bind to port 80 on all available IPv4 interfaces (denoted by the 0.0.0.0 IP address). Depending on your system’s configuration, the IP addresses may be different and only show individual IPs.

      If you are using HAProxy with IPv6, then the output may also include a line like the second one that is highlighted with an IPv6 specific interface and port error, in this case :::80. The first two :: characters indicate all available IPv6 interfaces, while the trailing :80 indicates the port.

      Even though your own system may have different conflicting interfaces and ports, the errors will be similar to the output shown here. With this output from journalctl you will be able to diagnose the issue using ss, ps, and ip commands in the following section of this tutorial.

      Troubleshooting with ss and ps Utilities

      To troubleshoot a cannot bind socket error you need to determine what other process is listening on the IP address and port that HAProxy is attempting to use, or if the IP address is available to HAProxy.

      For example, if another server like Nginx is configured to listen on port 8080 on all available IPv4 network interfaces, the full socket would be 0.0.0.0:8080. If HAProxy is also configured to use 0.0.0.0:8080 then the operating system will throw an EADDRINUSE error, and HAProxy will show a cannot bind socket error message, since it cannot claim the socket for itself.

      In the previous journalctl section, something was already bound to all the available IPv4 addresses (denoted by 0.0.0.0:80). Most modern Linux distributions include a utility called ss which can be used to gather information about the state of a system’s network sockets.

      The following command will determine the name of the process that is already bound to an IPv4 interface on port 80. Ensure that you substitute the port from the error message if it is different from 80 in the following command:

      • sudo ss -4 -tlnp | grep 80

      The flags to the ss command alter its default output in the following ways:

      • -4 restricts ss to only display IPv4-related socket information.
      • -t restricts the output to tcp sockets only.
      • -l displays all listening sockets with the -4 and -t restrictions taken into account.
      • -n ensures that port numbers are displayed, as opposed to protocol names like ‘httporhttps`. This is important since HAProxy may be attempting to bind to a non-standard port and a service name can be confusing as opposed to the actual port number.
      • -p outputs information about the process that is bound to a port.
      • | grep 80 limits the output to lines that contain the characters 80 so there are fewer lines that you have to examine

      Note: in this IPv4 and the following IPv6 example, if you do not have a line in your output with a matching port, then your cannot bind socket error may be derived from an EADDRNOTAVAIL error. Skip to the next section Troubleshooting with the ip Utility to examine the available IP addresses on your system.

      With all of those flags, you should receive output like the following:

      Output

      LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=40,fd=6))

      The first three fields are not important when troubleshooting a cannot bind socket error so they can be ignored. The important fields are the fourth (0.0.0.0:80), which matches the journalctl error that you discovered earlier, along with the last users:(("nginx",pid=40,fd=6)), specifically the pid=40 portion.

      If you have a cannot bind socket error that is related to an IPv6 interface, repeat the ss invocation, this time using the -6 flag to restrict the interfaces to the IPv6 network stack like this:

      • sudo ss -6 -tlnp |grep 80

      The -6 flag limits the ip command to IPv6 interfaces. If HAProxy is unable to bind to an IPv6 socket, you should have output like the following:

      Output

      LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=40,fd=7))

      Again, substitute the port number in question from your journalctl output if it is different from the highlighted 80 given here.

      In both these cases of IPv4 and IPv6 errors, the ss output indicates that there is a program with process ID 40 (the pid=40 in the output) that is bound to the 0.0.0.0:80 and [::]:80 interfaces respectively. This process is preventing HAProxy from starting since it already owns the port. To determine the name of the program, use the ps utility like this, substituting the process ID from your output in place of the highlighted 40 value in this example:

      You will receive output that is similar to the following:

      Output

      PID TTY TIME CMD 40 ? 00:00:00 nginx

      The highlighted nginx in the output is the name of the process that is listening on the interfaces. Now that you have the name of the program that is preventing HAProxy from starting, you can decide how to resolve the error. You could stop the nginx process, reconfigure nginx to listen on a different interface and port, or reconfigure HAProxy to avoid the port collision.

      It is important to note that the process may be different from nginx and the port and IP addresses may not always be 0.0.0.0 or [::] if you are diagnosing a cannot bind socket error. Oftentimes, different web servers and proxies will be in use on the same server. Each may be attempting to bind to different IPv4 ports and IPv6 interfaces to handle different web traffic. For example, a server that is configured with HAProxy listening on the IPv4 loopback address (also referred to as localhost) on port 8080 will show ss output like this:

      Output

      LISTEN 0 2000 127.0.0.1:8080 0.0.0.0:* users:(("haproxy",pid=545,fd=7))

      It is important to combine systemctl output, or journalctl output that indicates specific IP addresses and ports, with diagnostic data from ss, and then ps to narrow down the process that is causing HAProxy to fail to start.

      Sometimes when you are troubleshooting a cannot bind socket error message with ss and ps there will not be any output at all, which means that the error may not be caused by a socket conflict. The next section of this tutorial explains how to troubleshoot a cannot bind socket error using the ip utility.

      Troubleshooting with the ip Utility

      The previous section explained how an EADDRINUSE operating system error could cause a cannot bind socket error message. However, if you have examined ss and ps output and there is no socket conflict on your system, the issue may be caused by an EADDRNOTAVAIL operating system error instead. In this case HAProxy may be trying to bind to a socket that is not available to your operating system.

      To determine whether a cannot bind socket error is caused by an EADDRNOTAVAIL, examine both the IPv4 and IPv6 network interfaces on your system using the ip command.

      • sudo ip -4 -c address show
      • -4 restricts ip to only display IPv4-related interface information.
      • -c adds color coding to the output so that it is easier to parse visually.
      • address show displays the IP address for an interface, with the -4 and -c flags taken into account.

      You should receive output that looks similar to the following on any Linux distribution that includes the ip tool:

      Output

      1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 inet 203.0.113.1/24 brd 203.0.113.255 scope global eth0 valid_lft forever preferred_lft forever inet 192.0.2.1/24 brd 192.0.2.255 scope global eth0 valid_lft forever preferred_lft forever 3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 inet 198.51.100.1/24 brd 198.51.100.255 scope global eth1 valid_lft forever preferred_lft forever

      Make a note of your IP addresses that correspond to the highlighted examples in this output. Your IP addresses and network interfaces will be different than the examples shown here. You may have more or fewer interfaces, and each may have more or fewer addresses assigned to them. The important part is to note the IP addresses from ip.

      To examine IPv6 addresses that are assigned to your system, use the ip command with the -6 flag like this:

      • sudo ip -6 -c address show

      You should receive output like the following:

      Output

      1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 state UNKNOWN qlen 1000 inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 state UP qlen 1000 inet6 2604:a880:400:d1::3d3:6001/64 scope global valid_lft forever preferred_lft forever inet6 fe80::a4ff:aaff:fec9:24f8/64 scope link valid_lft forever preferred_lft forever

      Again note the highlighted values in this example output and look for the corresponding IPv6 addresses in your output.

      Once you have a list of addresses that are assigned to your system, you can try to find a matching IP address that corresponds to the cannot bind socket [x.x.x.x:80] error. If there is no IP address that matches, then HAProxy is likely configured to use an IP address that is not available to your system and the cannot bind socket error is being caused by the operating system throwing an EADDRNOTAVAIL error.

      To resolve the error you will need to edit your /etc/haproxy/haproxy.cfg file and change the bind address or addresses to an IP address that is available to your system based on the output of the ip command.

      For example, if /etc/haproxy/haproxy.cfg contained a bind line like the following using 198.51.100.123 as the IP address, but your system has 198.51.100.1 assigned based on the example output above, you will need to edit the bind line.

      Following this hypothetical example, this haproxy.cfg snippet shows the invalid IP address:

      /etc/haproxy/haproxy.cfg

      . . .
      frontend main
              bind 198.51.100.123:80
      

      A correct bind line that matches the IP address in the example ip output would look like this:

      /etc/haproxy/haproxy.cfg

      . . .
      frontend main
              bind 198.51.100.1:80
      

      Once you have edited /etc/haproxy/haproxy.cfg with the correct IP address, restart it using the systemctl command:

      • sudo systemctl restart haproxy.service

      Now examine HAProxy’s status and make sure that the output shows an active (running) line:

      • sudo systemctl status haproxy.service

      Output

      ● haproxy.service - HAProxy Load Balancer Loaded: loaded (/lib/systemd/system/haproxy.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2020-08-19 21:31:46 UTC; 17h ago Docs: man:haproxy(1) file:/usr/share/doc/haproxy/configuration.txt.gz Process: 487 ExecStartPre=/usr/sbin/haproxy -f $CONFIG -c -q $EXTRAOPTS (code=exited, status=0/SUCCESS) . . . Aug 19 21:31:46 d6cdd0c71489 systemd[1]: Started HAProxy Load Balancer.

      If you have resolved the cannot bind socket error your output should be similar to this example output. The highlighted lines that show HAProxy is active, and that the process was started successfully.

      Conclusion

      In this tutorial you learned how to troubleshoot an HAProxy cannot bind socket error message on both IPv4 and IPv6 interfaces. You learned how to use systemctl to examine the status of the HAProxy server and try to find error messages. You also learned how to use journalctl to examine the systemd logs for specific information about a cannot bind socket error.

      With the appropriate error messages from the systemd logs, you then learned about the ss utility and how to use it to examine the state of a system’s network sockets. After that you learned how to combine process ID information from ss with the ps utility to find the name of the process that is causing HAProxy to be unable to start.

      Finally, in the case of a cannot bind socket error that is related to an unavailable IPv4 or IPv6 address, you learned how to use the ip utility to examine available network interfaces on your system.



      Source link

      Apache Network Error AH00072: make_sock: could not bind to address



      Part of the Series:
      Common Apache Errors

      This tutorial series explains how to troubleshoot and fix some of the most common errors that you may encounter when using the Apache web server.

      Each tutorial in this series includes descriptions of common Apache configuration, network, filesystem, or permission errors. The series begins with an overview of the commands and log files that you can use to troubleshoot Apache. Subsequent tutorials examine specific errors in detail.

      Introduction

      An Apache AH00072: make_sock: could not bind to address error message is generated when there is another process listening on the same port that Apache is configured to use. Typically the port will be the standard port 80 for HTTP connections, or port 443 for HTTPS connections. However, any port conflict with another process can cause an AH00072 error.

      The error is derived from the underlying operating system system’s network stack. The issue is that only a single process can be bound to a port at any given time. If another web server like Nginx is configured to listen on port 80 and it is running, then Apache will not be able to claim the port for itself.

      To detect a port conflict with Apache, you will need to examine systemctl and journalctl output to determine the IP address and port that are causing the error. Then you can decide how to resolve the issue, whether it is by switching web servers, changing the IP address that Apache uses, the port, or any combination of these options.

      Troubleshooting with systemctl

      Following the troubleshooting steps from the How to Troubleshoot Common Apache Errors tutorial at the beginning of this series, the first step when you are troubleshooting an AH00072: make_sock: could not bind to address error message is to check Apache’s status with systemctl.

      If systemctl does not include output that describes the problem, then the last section of this tutorial, Troubleshooting Using journalctl Logs explains how to examine the systemd logs to find the conflicting port.

      The output from systemctl status will in many cases contain all the diagnostic information that you need to resolve the error. It will include the IP address that Apache is using, as well as the port that it is attempting to bind to. The output will also indicate how long Apache has been unable to start so that you can determine how long the issue has been affecting Apache.

      On Ubuntu and Debian-derived Linux distributions, run the following to check Apache’s status:

      Ubuntu and Debian Systems

      • sudo systemctl status apache2.service -l --no-pager

      On CentOS and Fedora systems, use this command to examine Apache’s status:

      CentOS and Fedora Systems

      • sudo systemctl status httpd.service -l --no-pager

      The -l flag will ensure that systemctl outputs the entire contents of a line, instead of substituting in ellipses () for long lines. The --no-pager flag will output the entire log to your screen without invoking a tool like less that only shows a screen of content at a time.

      Since you are troubleshooting an AH00072: make_sock error message, you should receive output that is similar to the following:

      Output

      ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: failed (Result: exit-code) since Tue 2020-07-28 13:58:40 UTC; 8s ago Docs: man:httpd.service(8) Process: 69 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited, status=1/FAILURE) Main PID: 69 (code=exited, status=1/FAILURE) Status: "Reading configuration..." Tasks: 213 (limit: 205060) Memory: 25.9M CGroup: /system.slice/containerd.service/system.slice/httpd.service Jul 28 13:58:40 e3633cbfc65e systemd[1]: Starting The Apache HTTP Server… Jul 28 13:58:40 e3633cbfc65e httpd[69]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80 Jul 28 13:58:40 e3633cbfc65e httpd[69]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80 Jul 28 13:58:40 e3633cbfc65e httpd[69]: no listening sockets available, shutting down Jul 28 13:58:40 e3633cbfc65e httpd[69]: AH00015: Unable to open logs Jul 28 13:58:40 e3633cbfc65e systemd[1]: httpd.service: Main process exited, code=exited, status=1/FAILURE Jul 28 13:58:40 e3633cbfc65e systemd[1]: httpd.service: Failed with result 'exit-code'. Jul 28 13:58:40 e3633cbfc65e systemd[1]: Failed to start The Apache HTTP Server.

      Note that your output may be slightly different if you are using an Ubuntu or Debian-derived distribution, where the name of the Apache process is not httpd but is apache2.

      This example systemctl output includes some highlighted lines from the systemd journal that describes the AH00072 error. These lines, both of which begin with (98)Address already in use: AH00072: make_sock: could not bind to address, give you all the information about the AH00072 error that you need to troubleshoot it further, so you can skip the following journalctl steps and instead proceed to the Troubleshooting with ss and ps Utilities section at the end of this tutorial.

      If your systemctl output does not give specific information about the IP address and port or ports that are causing the AH00072 error, you will need to examine journalctl output from the systemd logs. The following section explains how to use journalctl to troubleshoot an AH00072 error.

      Troubleshooting Using journalctl Logs

      If your systemctl output does not include specifics about an AH00072 error, you should proceed with using the journalctl command to examine systemd logs for Apache.

      On Ubuntu and Debian-derived systems, run the following command:

      • sudo journalctl -u apache2.service --since today --no-pager

      On CentOS, Fedora, and RedHat-derived systems, use this command to inspect the logs:

      • sudo journalctl -u httpd.service --since today --no-pager

      The --since today flag will limit the output of the command to log entries beginning at 00:00:00 of the current day only. Using this option will help restrict the volume of log entries that you need to examine when checking for errors.

      If Apache is unable to bind to a port that is in use, search through the output for lines that are similar to the following log entries, specifically lines that contain the AH00072 error code as highlighted in this example:

      Output

      -- Logs begin at Tue 2020-07-14 20:10:37 UTC, end at Tue 2020-07-28 14:01:40 UTC. -- . . . Jul 28 14:03:01 b06f9c91975d apachectl[71]: (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80 Jul 28 14:03:01 b06f9c91975d apachectl[71]: (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80 Jul 28 14:03:01 b06f9c91975d apachectl[71]: no listening sockets available, shutting down

      This output indicates two AH00072 errors. The first of these explains that Apache cannot bind to the [::]:80 address, which is port 80 on all available IPv6 interfaces. The next line, with the address 0.0.0.0:80, indicates Apache cannot bind to port 80 on all available IPv4 interfaces. Depending on your system’s configuration, the IP addresses may be different and only show individual IPs, and may only include IPv4 or IPv6 errors.

      Even though your own system may have different conflicting interfaces and ports, the errors will be similar to the output shown here. With output from journalctl you will be able to diagnose the issue using ss in the following section of this tutorial.

      Troubleshooting with ss and ps Utilities

      To troubleshoot an AH00072 error you need to determine what other process is listening on the IP address and port that Apache is attempting to use. Most modern Linux distributions include a utility called ss which can be used to gather information about the state of a system’s network sockets.

      In the previous journalctl section, something was already bound to the IPv4 and IPv6 addresses on port 80. The following command will determine the name of the process that is already bound to an IPv4 interface on port 80. Ensure that you substitute the port from the error message if it is different from 80 in the following command:

      • sudo ss -4 -tlnp | grep 80

      The flags to the ss command alter its default output in the following ways:

      • -4 restricts ss to only display IPv4-related socket information.
      • -t restricts the output to tcp sockets only.
      • -l displays all listening sockets with the -4 and -t restrictions taken into account.
      • -n ensures that port numbers are displayed, as opposed to protocol names like ‘httporhttps`. This is important since Apache may be attempting to bind to a non-standard port and a service name can be confusing as opposed to the actual port number.
      • -p outputs information about the process that is bound to a port.

      With all of those flags, you will receive output like the following:

      Output

      LISTEN 0 511 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=40,fd=6))

      The first three fields are not important when troubleshooting an AH00072 error so they can be ignored. The important fields are the fourth (0.0.0.0:80), which matches the journalctl error that you discovered earlier, along with the last users:(("nginx",pid=40,fd=6)), specifically the pid=40 portion.

      If you have an AH00072 error that is related to an IPv6 interface, repeat the ss invocation, this time using the -6 flag to restrict the interfaces to the IPv6 network stack like this:

      • sudo ss -6 -tlnp |grep 80

      Output

      LISTEN 0 511 [::]:80 [::]:* users:(("nginx",pid=40,fd=7))

      Again, substitute the port number in question from your journalctl output if it is different from the highlighted 80 given here.

      In both these cases of IPv4 and IPv6 errors, the ss output indicates that there is a program with process ID 40 (the pid=40 in the output) that is bound to the 0.0.0.0:80 and [::]:80 interfaces respectively. This process is preventing Apache from starting since it already owns the port. To determine the name of the program, use the ps utility like this, substituting the process ID from your output in place of the highlighted 40 value in this example:

      You will receive output that is similar to the following:

      Output

      PID TTY TIME CMD 40 ? 00:00:00 nginx

      The highlighted nginx in the output is the name of the process that is listening on the interfaces. Now that you have the name of the program that is preventing Apache from starting, you can decide how to resolve the error. You could stop the nginx process, reconfigure nginx to listen on a different interface and port, or reconfigure Apache to avoid the port collision.

      It is important to note that the process may be different from nginx and the port and IP addresses may not always be 0.0.0.0 or [::] if you are diagnosing an AH00072 error. Oftentimes, different web servers and proxies will be in use on the same server. Each may be attempting to bind to different IPv4 ports and IPv6 interfaces to handle different web traffic. For example, a server that is configured with HAProxy listening on the IPv4 loopback address (also referred to as localhost) on port 8080 will show ss output like this:

      Output

      LISTEN 0 2000 127.0.0.1:8080 0.0.0.0:* users:(("haproxy",pid=545,fd=7))

      It is important to combine systemctl output, or journalctl output that indicates specific IP addresses and ports, with diagnostic data from ss, and then ps to narrow down the process that is causing Apache to fail to start.

      Conclusion

      In this tutorial you learned how to troubleshoot an Apache AH00072 make_sock: could not bind to address error message on both IPv4 and IPv6 interfaces. You learned how to use systemctl to examine the status of the Apache server and try to find error messages. You also learned how to use journalctl to examine the systemd logs for specific information about an AH00072 error.

      With the appropriate error messages from the logs, you then learned about the ss utility and how to use it to examine the state of a system’s network sockets. After that you learned how to combine process ID information from ss with the ps utility to find the name of the process that is causing Apache to be unable to start.



      Source link

      Настройка BIND в качестве DNS-сервера частной сети на базе Ubuntu 18.04


      Введение

      Важным элементом управления конфигурацией и инфраструктурой сервера является поддержание удобного способа просмотра сетевых интерфейсов и IP-адресов по имени с помощью настройки корректной системы доменных имен (DNS). Использование полных доменных имен (FQDN), а не IP-адреса, для указания сетевых адресов облегчает настройку служб и приложений и повышает поддерживаемость файлов конфигурации. Настройка собственной DNS для вашей частной сети — это отличный способ совершенствования методов управления серверами.

      Из этого руководства вы узнаете, как выполнить настройку внутреннего DNS-сервера с помощью программного обеспечения сервера имен BIND (BIND9) на Ubuntu 18.04, которое может быть использовано вашими серверами для предоставления частных имен хостов и частных IP-адресов. Это служит центральным средством для управления внутренними именами хостов и частными IP-адресами, что необходимо при расширении вашей среды до более чем нескольких хостов.

      Версию CentOS, используемую в данном руководстве, можно найти здесь.

      Предварительные требования

      Для выполнения данного руководства вам потребуется следующая инфраструктура. Создайте каждый сервер в одном центре обработки данных *с активированной *опцией частной сети:

      • Свежий сервер Ubuntu 18.04, который будет использоваться в качестве основного DNS-сервера, ns1.
      • (Рекомендуется) Второй сервер Ubuntu 18.04, который используется в качестве дополнительного DNS-сервера, ns2.
      • Дополнительные серверы в одном центре обработки данных, которые будут использовать ваши DNS-серверы.

      На каждом из этих серверов необходимо настроить административный доступ с помощью пользователя sudo и брандмауэра согласно инструкциям нашего руководства по начальной настройке сервера Ubuntu 18.04.

      Если вы не знакомы с концепцией DNS, рекомендуем ознакомиться минимум с первыми тремя частями нашего руководства Введение в управление DNS.

      Пример инфраструктуры и целей

      В рамках данной статьи мы предполагаем следующее:

      • У нас есть два сервера, которые будут назначены в качестве наших серверов имен DNS. В этом руководстве мы будем использовать наименования ns1 и ns2.
      • У нас есть два дополнительных клиентских сервера, которые будут использовать созданную нами инфраструктуру DNS. В этом руководстве мы будем использовать наименования host1 и host2. Вы можете добавить любое количество, которое захотите, для вашей инфраструктуры.
      • Все эти серверы существуют в одном центре обработки данных. Мы полагаем, что это центр обработки данных nyc3.
      • Для всех этих серверов активирована опция частной сети (и в подсети 10.128.0.0/16; вам, возможно, нужно будет отредактировать эти параметры для ваших серверов).
      • Все серверы подключены к проекту, который запущен на example.com. Поскольку наша система DNS будет полностью внутренней и частной, вам не нужно будет приобретать доменное имя. Однако использование собственного домена может помочь избежать конфликтов с доменами с публичной маршрутизацией.

      С учетом этих предположений мы решили, что будет полезно использовать схему именования, которая использует nyc3.example.com для обращения к нашей частной подсети или зоне. Таким образом, частным полным доменным именем (FQDN) для host1 будет host1.nyc3.example.com. Соответствующую информацию см. в следующей таблице:

      ХостРольЧастное FQDNЧастный IP-адрес
      ns1Основной DNS-серверns1.nyc3.example.com10.128.10.11
      ns2Дополнительный DNS-серверns2.nyc3.example.com10.128.20.12
      host1Стандартный хост 1host1.nyc3.example.com10.128.100.101
      host2Стандартный хост 2host2.nyc3.example.com10.128.200.102

      Примечание: существующая настройка будет отличаться, примеры имен и IP-адресов будут использоваться для демонстрации того, как выполнить настройку DNS-сервера для получения работающей внутренней DNS. У вас должна быть возможность легко адаптировать данную настройку для вашей среды, заменив имена хостов и частные IP-адреса на собственные. Нет необходимости использовать имя региона центра обработки данных в схеме присвоения имен, но мы используем его для обозначения хостов, принадлежащих к частной сети конкретного центра обработки данных. Если вы используете несколько центров обработки данных, вы можете настроить внутреннюю DNS внутри каждого отдельного центра обработки данных.

      К концу данного руководства мы получим основной DNS-сервер, ns1, и, в качестве опции, дополнительный DNS-сервер, ns2, который будет служит в качестве резервного сервера.

      Давайте начнем с установки нашего основного DNS-сервера, ns1.

      Установка BIND на DNS-серверах

      Примечание: красным цветом выделяется важная информация! Он часто будет использоваться для чего-то, что необходимо заменить на собственные настройки или того, что нужно изменить или добавить в файл конфигурации. Например, если вы увидите что-то вроде host1.nyc3.example.com, замените эти данные на FQDN вашего сервера. Аналогичным образом, если вы увидите host1_private_IP, замените эти данные на частный IP-адрес вашего сервера.

      На обоих DNS-серверах, ns1 и ns2, обновите кэш пакета apt с помощью следующей команды:

      Теперь можно переходить к установке BIND:

      • sudo apt-get install bind9 bind9utils bind9-doc

      Настройка режима IPv4 для Bind

      Прежде чем продолжить, давайте настроим режим IPv4 в BIND, так как наша частная сеть использует исключительно IPv4. На обоих серверах отредактируйте файл настроек по умолчанию bind9 с помощью следующей команды:

      • sudo nano /etc/default/bind9

      Добавьте “-4” в конец параметра OPTIONS. Результат будет выглядеть следующим образом:

      /etc/default/bind9

      . . .
      OPTIONS="-u bind -4"
      

      Сохраните файл и закройте его после завершения.

      Перезапустите BIND для вступления изменений в силу:

      • sudo systemctl restart bind9

      Теперь, после установки BIND, давайте настроим основной DNS-сервер.

      Настройка основного DNS-сервера

      Конфигурация BIND состоит из множества файлов, которые включены в основной файл конфигурации, named.conf. Эти имена файлов начинаются с named, потому что это имя процесса, который запускает BIND (сокращение от “domain name daemon”). Мы начнем с настройки файла параметров.

      Настройка файла параметров

      На сервере ns1 откройте файл named.conf.options для редактирования:

      • sudo nano /etc/bind/named.conf.options

      Над существующим блоком options создайте новый блок ACL (список контроля доступа) под названием “trusted”. Именно здесь мы создадим список клиентов, для которых мы будем разрешать рекурсивные DNS-запросы (т. е. запросы от ваших серверов, находящихся в том же центре обработки данных, что и ns1). С помощью нашего примера частных IP-адресов мы добавим ns1, ns2, host1 и host2 в наш список надежных клиентов:

      /etc/bind/named.conf.options — 1 of 3

      acl "trusted" {
              10.128.10.11;    # ns1 - can be set to localhost
              10.128.20.12;    # ns2
              10.128.100.101;  # host1
              10.128.200.102;  # host2
      };
      
      options {
      
              . . .
      

      Теперь, когда у нас есть список доверенных DNS-клиентов, нам нужно отредактировать блок options. В настоящее время начало блока выглядит следующим образом:

      /etc/bind/named.conf.options — 2 of 3

              . . .
      };
      
      options {
              directory "/var/cache/bind";
              . . .
      }
      

      Под директивой directory добавьте выделенные цветом строки конфигурации (и замените в соответствующем IP-адресе ns1), чтобы результат выглядел примерно следующим образом:

      /etc/bind/named.conf.options — 3 of 3

              . . .
      
      };
      
      options {
              directory "/var/cache/bind";
      
              recursion yes;                 # enables resursive queries
              allow-recursion { trusted; };  # allows recursive queries from "trusted" clients
              listen-on { 10.128.10.11; };   # ns1 private IP address - listen on private network only
              allow-transfer { none; };      # disable zone transfers by default
      
              forwarders {
                      8.8.8.8;
                      8.8.4.4;
              };
      
              . . .
      };
      

      После завершения редактирования сохраните и закройте файл named.conf.options. Согласно конфигурация выше, только ваши собственные серверы (т. е. доверенные) смогут запрашивать у вашего DNS-сервера внешние домены.

      Далее мы настроим локальный файл, чтобы задать ваши DNS-зоны.

      Настройка локального файла

      На сервере ns1 откройте файл named.conf.local для редактирования:

      • sudo nano /etc/bind/named.conf.local

      Файл должен содержать только несколько комментариев. Здесь мы зададим наши зоны. DNS-зоны определяют конкретную область для управления и определения записей DNS. Поскольку наши домены будут находиться в субдомене nyc3.example.com, мы будем использовать его в качестве зоны прямого просмотра. Поскольку частные IP-адреса нашего сервера находятся в пространстве IP-адресов 10.128.0.0/16, мы создадим зону обратного просмотра, чтобы мы могли определять обратный просмотр в этом диапазоне.

      Добавьте зону прямого просмотра со следующими строками, заменив имя зоны на собственное, и закрытый IP-адрес дополнительного DNS сервера в директиве allow-transfer:

      /etc/bind/named.conf.local — 1 of 2

      zone "nyc3.example.com" {
          type master;
          file "/etc/bind/zones/db.nyc3.example.com"; # zone file path
          allow-transfer { 10.128.20.12; };           # ns2 private IP address - secondary
      };
      

      Если, согласно нашему предположению, нашей частной подсетью является 10.128.0.0/16, добавьте зону обратного просмотра с помощью следующих строк (обратите внимание, что имя зоны обратного просмотра начинается с “128.10”, что представляет собой битное преобразование “10.128"​):

      /etc/bind/named.conf.local — 2 of 2

          . . .
      };
      
      zone "128.10.in-addr.arpa" {
          type master;
          file "/etc/bind/zones/db.10.128";  # 10.128.0.0/16 subnet
          allow-transfer { 10.128.20.12; };  # ns2 private IP address - secondary
      };
      

      Если ваши серверы охватывают несколько частных подсетей, но находятся в одном центре обработки данных, обязательно указывайте дополнительную зону и файл зоны для каждой отдельной подсети. После добавления всех необходимых зон сохраните и закройте файл named.conf.local.

      Теперь, когда наши зоны указаны в BIND, нам нужно создать соответствующие файлы для зоны прямого и обратного просмотра.

      Создание файла для зоны прямого просмотра

      Файл зоны прямого просмотра — это место, где мы будем определять DNS-записи для прямого просмотра DNS. Т. е., когда DNS получает запрос имени, например, "host1.nyc3.example.com”, будет выполняться поиск в файле зоны прямого просмотра для получения соответствующего частного IP-адреса для host1.

      Давайте создадим директорию, в которой будут находиться наши файлы зоны. Согласно конфигурации named.conf.local, это должна быть директория /etc/bind/zones:

      • sudo mkdir /etc/bind/zones

      При создании нашего файла зоны для прямого просмотра мы будем опираться в качестве примера на файл зоны db.local. Скопируйте его в надлежащее место с помощью следующих команд:

      • sudo cp /etc/bind/db.local /etc/bind/zones/db.nyc3.example.com

      Теперь необходимо отредактировать наш файл зоны для прямого просмотра:

      • sudo nano /etc/bind/zones/db.nyc3.example.com

      Первоначально он будет выглядеть примерно следующим образом:

      /etc/bind/zones/db.nyc3.example.com — original

      $TTL    604800
      @       IN      SOA     localhost. root.localhost. (
                                    2         ; Serial
                               604800         ; Refresh
                                86400         ; Retry
                              2419200         ; Expire
                               604800 )       ; Negative Cache TTL
      ;
      @       IN      NS      localhost.      ; delete this line
      @       IN      A       127.0.0.1       ; delete this line
      @       IN      AAAA    ::1             ; delete this line
      

      Во-первых, вам необходимо отредактировать запись SOA. Замените первую запись “localhost” на полное доменное имя (FQDN) ns1, а затем замените “root.localhost” на “admin.nyc3.example.com”. При каждом изменении файла зоны вам нужно будет увеличивать значение serial, прежде чем перезапускать процесс named. Мы увеличим значение до “3”. Теперь файл должен выглядеть примерно следующим образом:

      /etc/bind/zones/db.nyc3.example.com — updated 1 of 3

      @       IN      SOA     ns1.nyc3.example.com. admin.nyc3.example.com. (
                                    3         ; Serial
      
                                    . . .
      

      Далее удалите три записи в конце файла (после записи SOA). Если вы уверены, какие строки следует удалить, удаляйте строки с комментарием “delete this line”.

      В конце файла добавьте записи для имени сервера со следующими строками (замените имена на собственные). Обратите внимание, что во втором столбце указывается, что это записи “NS”.

      /etc/bind/zones/db.nyc3.example.com — updated 2 of 3

      . . .
      
      ; name servers - NS records
          IN      NS      ns1.nyc3.example.com.
          IN      NS      ns2.nyc3.example.com.
      

      Теперь добавьте записи A для ваших хостов, которые принадлежат к этой зоне. Это может быть любой сервер, имя которого будет заканчиваться на “.nyc3.example.com” (замените имена и частные IP-адреса). Используя приведенные в качестве примера имена и частные IP-адреса, мы добавим записи A для ns1, ns2, host1 и host2 примерно таким образом:

      /etc/bind/zones/db.nyc3.example.com — updated 3 of 3

      . . .
      
      ; name servers - A records
      ns1.nyc3.example.com.          IN      A       10.128.10.11
      ns2.nyc3.example.com.          IN      A       10.128.20.12
      
      ; 10.128.0.0/16 - A records
      host1.nyc3.example.com.        IN      A      10.128.100.101
      host2.nyc3.example.com.        IN      A      10.128.200.102
      

      Сохраните и закройте файл db.nyc3.example.com.

      Полученный нами в итоге пример файла зоны для прямого просмотра выглядит следующим образом:

      /etc/bind/zones/db.nyc3.example.com — updated

      $TTL    604800
      @       IN      SOA     ns1.nyc3.example.com. admin.nyc3.example.com. (
                        3     ; Serial
                   604800     ; Refresh
                    86400     ; Retry
                  2419200     ; Expire
                   604800 )   ; Negative Cache TTL
      ;
      ; name servers - NS records
           IN      NS      ns1.nyc3.example.com.
           IN      NS      ns2.nyc3.example.com.
      
      ; name servers - A records
      ns1.nyc3.example.com.          IN      A       10.128.10.11
      ns2.nyc3.example.com.          IN      A       10.128.20.12
      
      ; 10.128.0.0/16 - A records
      host1.nyc3.example.com.        IN      A      10.128.100.101
      host2.nyc3.example.com.        IN      A      10.128.200.102
      

      Теперь пришло время перейти к файлу (файлам) зоны для обратного просмотра.

      Создание файла (файлов) зоны для обратного просмотра

      Файлы зоны для обратного просмотра служат местом, где мы будем определять PTR записей DNS для обратного просмотра DNS. Т. е., когда DNS получает запрос для IP-адреса, например, “10.128.100.101”, она будет выполнять поиск по файлу (файлам) зоны для обратного просмотра, чтобы получить соответствующее полное доменное имя, в нашем случае это “host1.nyc3.example.com”.

      В ns1 для каждой зоны обратного просмотра, заданной в файле named.conf.local, необходимо создать файл зоны для обратного просмотра. При создании нашего файла (или файлов) зоны для обратного просмотра мы будем опираться в качестве примера на файл зоны db.local. Скопируйте его в надлежащее место с помощью следующих команд (замените имя файла назначения, чтобы оно соответствовало определению вашей зоны для обратного просмотра):

      • sudo cp /etc/bind/db.127 /etc/bind/zones/db.10.128

      Отредактируйте файл зоны для обратного просмотра, который соответствует зоне(-ам), определенной(-ым) в named.conf.local:

      • sudo nano /etc/bind/zones/db.10.128

      Первоначально он будет выглядеть примерно следующим образом:

      /etc/bind/zones/db.10.128 — original

      $TTL    604800
      @       IN      SOA     localhost. root.localhost. (
                                    1         ; Serial
                               604800         ; Refresh
                                86400         ; Retry
                              2419200         ; Expire
                               604800 )       ; Negative Cache TTL
      ;
      @       IN      NS      localhost.      ; delete this line
      1.0.0   IN      PTR     localhost.      ; delete this line
      

      Как и в случае с файлом зоны для прямого просмотра, вам нужно изменить запись SOA и увеличить значение serial. Он должен выглядеть следующим образом:

      /etc/bind/zones/db.10.128 — updated 1 of 3

      @       IN      SOA     ns1.nyc3.example.com. admin.nyc3.example.com. (
                                    3         ; Serial
      
                                    . . .
      

      Теперь удалите две записи в конце файла (после записи SOA). Если вы уверены, какие строки следует удалить, удаляйте строки с комментарием “delete this line”.

      В конце файла добавьте записи для имени сервера со следующими строками (замените имена на собственные). Обратите внимание, что во втором столбце указывается, что это записи “NS”.

      /etc/bind/zones/db.10.128 — updated 2 of 3

      . . .
      
      ; name servers - NS records
            IN      NS      ns1.nyc3.example.com.
            IN      NS      ns2.nyc3.example.com.
      

      Затем добавьте записи PTR для всех ваших серверов, чей IP-адрес соответствует подсети файла зоны, который вы редактируете. В нашем примере это будут все наши хосты, поскольку все они находятся в подсети 10.128.0.0/16. Обратите внимание, что первый столбец включает два последних байта частных IP-адресов ваших серверов в обратном порядке. Обязательно замените имена и частные IP-адреса согласно данным ваших серверов:

      /etc/bind/zones/db.10.128 — updated 3 of 3

      . . .
      
      ; PTR Records
      11.10   IN      PTR     ns1.nyc3.example.com.    ; 10.128.10.11
      12.20   IN      PTR     ns2.nyc3.example.com.    ; 10.128.20.12
      101.100 IN      PTR     host1.nyc3.example.com.  ; 10.128.100.101
      102.200 IN      PTR     host2.nyc3.example.com.  ; 10.128.200.102
      

      Сохраните и закройте файл зоны для обратного просмотра (повторите описанные в данном разделе действия, если вам потребуется добавить дополнительные файлы зоны для обратного просмотра).

      Полученный нами в итоге пример файла зоны для обратного просмотра выглядит следующим образом:

      /etc/bind/zones/db.10.128 — updated

      $TTL    604800
      @       IN      SOA     nyc3.example.com. admin.nyc3.example.com. (
                                    3         ; Serial
                               604800         ; Refresh
                                86400         ; Retry
                              2419200         ; Expire
                               604800 )       ; Negative Cache TTL
      ; name servers
            IN      NS      ns1.nyc3.example.com.
            IN      NS      ns2.nyc3.example.com.
      
      ; PTR Records
      11.10   IN      PTR     ns1.nyc3.example.com.    ; 10.128.10.11
      12.20   IN      PTR     ns2.nyc3.example.com.    ; 10.128.20.12
      101.100 IN      PTR     host1.nyc3.example.com.  ; 10.128.100.101
      102.200 IN      PTR     host2.nyc3.example.com.  ; 10.128.200.102
      

      Мы завершили редактирование наших файлов, и теперь мы можем проверить наши файлы на ошибки.

      Проверка синтаксиса конфигурации BIND

      Запустите следующую команду для проверки синтаксиса файлов named.conf*:

      Если в ваших именованных файлах конфигурации нет ошибок в синтаксисе, вы должны будете вернуться в командную строку без каких-либо сообщений об ошибках. При обнаружении проблем с файлами конфигурации вы должны будете просмотреть сообщение об ошибке и раздел «Настройка основного DNS сервера», а затем снова воспользоваться командой named-checkconf.

      Команда named-checkzone может использоваться для проверки корректности ваших файлов зоны. Первый аргумент команды указывает имя зоны, а второй аргумент определяет соответствующий файл зоны, оба из которых определены в named.conf.local​​​.

      Например, чтобы проверить конфигурацию зоны для прямого просмотра “nyc3.example.com”, запустите следующую команду (измените на ваши имена зоны для прямого просмотра и файла):

      • sudo named-checkzone nyc3.example.com db.nyc3.example.com

      А чтобы проверить конфигурацию зоны для обратного просмотра “128.10.in-addr.arpa”, запустите следующую команду (замените на данные, соответствующие вашей зоне для обратного просмотра и файлу):

      • sudo named-checkzone 128.10.in-addr.arpa /etc/bind/zones/db.10.128

      Когда все файлы конфигурации и зоны не будут иметь ошибок, вы должны будете перезапустить службу BIND.

      Перезапуск BIND

      Перезапустите BIND:

      • sudo systemctl restart bind9

      Если у вас есть настроенный брандмауэр UFW, откройте доступ к BIND с помощью следующей команды:

      Теперь ваш основной DNS-сервер настроен и может отвечать на запросы DNS. Давайте перейдем к созданию дополнительного DNS-сервера.

      Настройка дополнительного DNS-сервера

      В большинстве сред правильным решением будет создание дополнительного DNS-сервера, который будет отвечать на запросы, если основной сервер окажется недоступным. К счастью, настройка дополнительного DNS-сервера выполняется намного проще.

      На сервере ns2 отредактируйте файл named.conf.options:

      • sudo nano /etc/bind/named.conf.options

      В верхней части файла добавьте ACL с частными IP-адресами всех ваших доверенных серверов:

      /etc/bind/named.conf.options — updated 1 of 2 (secondary)

      acl "trusted" {
              10.128.10.11;   # ns1
              10.128.20.12;   # ns2 - can be set to localhost
              10.128.100.101;  # host1
              10.128.200.102;  # host2
      };
      
      options {
      
              . . .
      

      Под директивой directory добавьте следующие строки:

      /etc/bind/named.conf.options — updated 2 of 2 (secondary)

              recursion yes;
              allow-recursion { trusted; };
              listen-on { 10.128.20.12; };      # ns2 private IP address
              allow-transfer { none; };          # disable zone transfers by default
      
              forwarders {
                      8.8.8.8;
                      8.8.4.4;
              };
      

      Сохраните и закройте файл named.conf.options. Этот файл должен выглядеть так же, как файл named.conf.options сервера ns1, за исключением того, что его необходимо настроить на прослушивание частного IP-адреса ns2.

      Теперь необходимо отредактировать файл named.conf.local:

      • sudo nano /etc/bind/named.conf.local

      Определите slave-зоны, соответствующие master-зонам основного DNS-сервера. Обратите внимание, что в качестве типа используется slave, в файле отсутствует путь, и существует директива masters, которая должна быть настроена на частный IP-адрес основного DNS-сервера. Если вы определили несколько зон для обратного просмотра на основном DNS-сервере, обязательно проверьте, что все они были добавлены на этом этапе:

      /etc/bind/named.conf.local — updated (secondary)

      zone "nyc3.example.com" {
          type slave;
          file "db.nyc3.example.com";
          masters { 10.128.10.11; };  # ns1 private IP
      };
      
      zone "128.10.in-addr.arpa" {
          type slave;
          file "db.10.128";
          masters { 10.128.10.11; };  # ns1 private IP
      };
      

      Сохраните и закройте файл named.conf.local.

      Запустите следующую команду для проверки валидности ваших файлов конфигурации:

      После выполнения проверки перезапустите BIND:

      • sudo systemctl restart bind9

      Разрешите подключение DNS к серверу, внеся изменения в правила брандмауэра UFW:

      Теперь у вас есть основной и дополнительный DNS-серверы для имени частной сети и преобразования IP-адреса. Теперь вам нужно настроить ваши клиентские серверы, чтобы они могли использовать ваши частные DNS-серверы.

      Настройка DNS-клиентов

      Прежде чем все ваши серверы в доверенном ACL смогут отправлять запросы на ваши DNS-серверы, вы должны настроить для каждого из них использование ns1 и ns2 в качестве сервера имен. Этот процесс варьируется в зависимости от операционной системы, но для большинства дистрибутивов Linux он подразумевает добавление ваших серверов доменных имен в файл /etc/resolv.conf.

      Клиенты Ubuntu 18.04

      На Ubuntu 18.04 настройка сетевого взаимодействия выполняется с помощью Netplan, абстракции, которая позволяет вам записывать стандартную конфигурацию сети и применять ее к несовместимому сетевому ПО, отвечающему за бекэнд. Для настройки DNS нам потребуется записать файл конфигурации Netplan.

      Во-первых, найдите устройство, связанное с вашей частной сетью, отправив частной подсети команду ip address:

      • ip address show to 10.128.0.0/16

      Output

      3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000 inet 10.128.100.101/16 brd 10.128.255.255 scope global eth1 valid_lft forever preferred_lft forever

      В этом примере используется частный интерфейс eth1.

      Далее необходимо создать новый файл в /etc/netplan с именем 00-private-nameservers.yaml:

      • sudo nano /etc/netplan/00-private-nameservers.yaml

      Вставьте в файл следующее содержимое. Вам потребуется изменить интерфейс частной сети, адреса ваших DNS-серверов ns1 и ns2, а также зону DNS:

      Примечание: Netplan использует формат сериализации данных YAML для своих файлов конфигурации. Поскольку YAML использует структурирование текста и пробелы для определения структуры данных, убедитесь, что ваше определение имеет равномерное структурирование текста во избежание ошибок.

      /etc/netplan 00-private-nameservers.yaml

      network:
          version: 2
          ethernets:
              eth1:                                 # Private network interface
                  nameservers:
                      addresses:
                      - 10.128.10.11                # Private IP for ns1
                      - 10.132.20.12                # Private IP for ns2
                      search: [ nyc3.example.com ]  # DNS zone
      
      

      Сохраните файл и закройте его после завершения.

      Затем вы должны сообщить Netplan о необходимости использования нового файла конфигурации с помощью команды netplan try. При наличии проблем, которые приводят к потере подключения к сети, Netplan будет автоматически перезапускать изменения по истечении определенного периода времени:

      Output

      Warning: Stopping systemd-networkd.service, but it can still be activated by: systemd-networkd.socket Do you want to keep these settings? Press ENTER before the timeout to accept the new configuration Changes will revert in 120 seconds

      Если счетчик в нижней части обновляется корректно, это значит, что новой конфигурации удалось по крайней мере не повредить ваше соединение SSH. Нажмите ENTER, чтобы принять изменения в конфигурации.

      Теперь проверьте DNS-преобразователь системы, чтобы определить, применены ли изменения в конфигурацию DNS:

      • sudo systemd-resolve --status

      Прокрутите вниз, пока не увидите раздел для вашего интерфейса частной сети. Вы должны увидеть частные IP-адреса ваших DNS-серверов, которые будут перечислены в первую очередь, а за ними идут резервные значения. Ваш домен должен находиться в строке DNS Domain:

      Output

      . . . Link 3 (eth1) Current Scopes: DNS LLMNR setting: yes MulticastDNS setting: no DNSSEC setting: no DNSSEC supported: no DNS Servers: 10.128.10.11 10.128.20.12 67.207.67.2 67.207.67.3 DNS Domain: nyc3.example.com . . .

      Ваш клиент должен быть настроен на использование ваших внутренних DNS-серверов.

      Клиенты Ubuntu 16.04 и Debian

      В серверах Ubuntu 16.04 и Debian вы можете изменить файл /etc/network/interfaces:

      • sudo nano /etc/network/interfaces

      Внутри найдите строку dns-nameservers и добавьте ваши серверы доменных имен в начало списка, который уже добавлен в файл. Под этой строкой добавьте опцию dns-search, указывающую на базовый домен вашей инфраструктуры. В нашем случае это будет “nyc3.example.com”:

      /etc/network/interfaces

          . . .
      
          dns-nameservers 10.128.10.11 10.128.20.12 8.8.8.8
          dns-search nyc3.example.com
      
          . . .
      

      Сохраните файл и закройте его после завершения.

      Перезапустите ваши сетевые службы, применив изменения с помощью следующих команд. Убедитесь, что вы заменили eth0 на имя вашего сетевого интерфейса:

      • sudo ifdown --force eth0 && sudo ip addr flush dev eth0 && sudo ifup --force eth0

      В результате будет выполнен перезапуск вашей сети без отключения текущего подключения. Если все работает корректно, вы должны увидеть примерно следующее:

      Output

      RTNETLINK answers: No such process Waiting for DAD... Done

      Еще раз проверьте, что ваши настройки были применены, введя следующую команду:

      Вы должны увидеть ваши серверы доменных имен в файле /etc/resolv.conf, а также ваш домен поиска:

      Output

      # Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8) # DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN nameserver 10.128.10.11 nameserver 10.128.20.12 nameserver 8.8.8.8 search nyc3.example.com

      Ваш клиент настроен для использования ваших DNS-серверов.

      Клиенты CentOS

      В CentOS, RedHat и Fedora Linux отредактируйте файл /etc/sysconfig/network-scripts/ifcfg-eth0. Возможно, вам придется заменить eth0 на имя вашего основного сетевого интерфейса:

      • sudo nano /etc/sysconfig/network-scripts/ifcfg-eth0

      Найдите опции DNS1 и DNS2 и задайте для них частные IP-адреса ваших основного и дополнительного серверов доменных имен. Добавьте параметр DOMAIN, используя базовый домен вашей инфраструктуры. В этом руководстве это будет “nyc3.example.com”:

      /etc/sysconfig/network-scripts/ifcfg-eth0

      . . .
      DNS1=10.128.10.11
      DNS2=10.128.20.12
      DOMAIN='nyc3.example.com'
      . . .
      

      Сохраните файл и закройте его после завершения.

      Перезапустите сетевую службу с помощью следующей команды:

      • sudo systemctl restart network

      Команда может зависнуть на несколько секунд, но через короткое время вы должны вернуться в командную строку.

      Убедитесь, что изменения вступили в силу, введя следующую команду:

      Вы должны увидеть ваши серверы доменных имен и домена поиска в списке:

      /etc/resolv.conf

      nameserver 10.128.10.11
      nameserver 10.128.20.12
      search nyc3.example.com
      

      Ваш клиент теперь может подключиться и использовать ваши DNS-серверы.

      Тестирование клиентов

      Используйте nslookup для проверки того, могут ли ваши клиенты отправлять запросы вашим серверам доменных имен. У вас должна быть возможность сделать это для всех клиентов, которые были настроены и находятся в доверенном ACL.

      Для клиентов CentOS вам может потребоваться установка утилиты с помощью следующей команды:

      • sudo yum install bind-utils

      Мы можем начать выполнять прямой просмотр.

      Прямой просмотр

      Например, мы можем выполнить прямой просмотр для получения IP-адреса host1.nyc3.example.com с помощью следующей команды:

      Запрос “host1” расширяется до “host1.nyc3.example.com”, потому что опция search задана для вашего частного субдомена, а запросы DNS будут пытаться просмотреть этот субдомен перед поиском по всему хосту. Результат описанной выше команды будет выглядеть следующим образом:

      Output

      Server: 127.0.0.53 Address: 127.0.0.53#53 Non-authoritative answer: Name: host1.nyc3.example.com Address: 10.128.100.101

      Теперь мы можем проверить обратный просмотр.

      Обратный просмотр

      Чтобы протестировать обратный просмотр, отправьте DNS-серверу запрос на частный IP-адрес host1:

      Результат будет выглядеть следующим образом:

      Output

      11.10.128.10.in-addr.arpa name = host1.nyc3.example.com. Authoritative answers can be found from:

      Если все имена и IP-адреса будут передавать правильные значения, это означает, что ваши файлы зоны настроены надлежащим образом. Если вы получите неожиданные значения, обязательно проверьте файлы зоны на вашем основном DNS-сервере (например, db.nyc3.example.com и db.10.128).

      Поздравляем! Ваши внутренние DNS-серверы настроены надлежащим образом! Теперь мы перейдем к сохранению записей зоны.

      Сохранение DNS-записей

      Теперь, когда у вас есть работающий внутренний DNS-сервер, вам нужно хранить ваши записи DNS, чтобы они точно отражали среду сервера.

      Добавление хоста в DNS

      При добавлении хоста в вашу среду (в одном центре обработки данных) вам нужно добавить его в DNS. Здесь представлен список шагов, которые вам нужно предпринять:

      Основной сервер доменных имен

      • Файл зоны для прямого просмотра: добавьте запись A для нового хоста, увеличив значение “Serial”
      • Файл зоны для обратного просмотра: добавьте запись PTR для нового хоста, увеличив значение “Serial”
      • Добавьте частный IP-адрес вашего нового хоста в доверенный ACL (named.conf.options)

      Протестируйте ваши файлы конфигурации:

      • sudo named-checkconf
      • sudo named-checkzone nyc3.example.com db.nyc3.example.com
      • sudo named-checkzone 128.10.in-addr.arpa /etc/bind/zones/db.10.128

      Затем перезагрузите BIND:

      • sudo systemctl reload bind9

      Ваш основной сервер должен быть настроен для использования нового хоста.

      Дополнительный сервер доменных имен

      • Добавьте частный IP-адрес вашего нового хоста в доверенный ACL (named.conf.options)

      Проверьте синтаксис конфигурации:

      Затем перезагрузите BIND:

      • sudo systemctl reload bind9

      Ваш вторичный сервер теперь будет принимать подключения с нового хоста.

      Настройка нового хоста для использования вашей DNS

      • Настройте /etc/resolv.conf для использования ваших DNS-серверов
      • Выполните проверку с помощью nslookup

      Удаление хоста из DNS

      Если вы удалите хост из вашей среды или захотите просто убрать его из DNS, просто удалите все данные, которые были добавлены при добавлении сервера в DNS (т. е. выполните описанные выше шаги в обратно порядке).

      Заключение

      Теперь вы можете обращаться к интерфейсам серверов вашей частной сети по имени, а не по IP-адресу. Это упрощает настройку служб и приложений, поскольку вам больше не нужно запоминать частные IP-адреса, а файлы будет легче читать и понимать. Кроме того, теперь вы можете изменять свои конфигурации для работы с новыми серверами в одном месте, на вашем основном DNS-сервере, вместо того чтобы редактировать целых набор самых разных файлов.

      Когда ваш внутренний DNS-сервер был настроен, а файлы конфигурации используют частные FQDN для указания сетевых подключений, *критически *важно, чтобы ваши DNS-сервера обслуживались надлежащим образом. Если оба сервера окажутся недоступны, ваши службы и приложения, которые опираются на них при работе, не смогут нормально функционировать. Именно поэтому рекомендуется настроить для вашей DNS минимум один дополнительный сервер и сохранять рабочиие резервные копии всех серверов.



      Source link