This tip is really usefull if you use virtual ips.
Imagine you are using keepalived + haproxy on your loadbalancers in active/active mode.
You have 2 virtual IPs one is on the first load balancer and the other is on the second.
Now in your haproxy.cfg you have to bind these IPs, the probem is that one of the virtual IPs is not on the current loadbalancer, so haproxy will refuse to start with the following error:Starting proxy appli1-rewrite: cannot bind socket.
The common solution is to listen on0.0.0.0, but it not always practical on wanted, especially if you want to have another server using the same port but on another ip, or if you only want to listen on internal interfaces.
The solution is asysctlthat will allow any software to bind an IP even if it’s not up yet:
# sysctl -w net.ipv4.ip_nonlocal_bind=1
You should put this in/etc/sysctl.confto make this change permanent.
# echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.conf
sysctl命令详解
sysctl配置与显示在/proc/sys目录中的内核参数。
可以用sysctl来设置或重新设置联网功能,如IP转发、IP碎片去除以及源路由检查等。
用户只需要编辑/etc/sysctl.conf文件,即可手工或自动执行由sysctl控制的功能。
命令格式:
sysctl [-n] [-e] -w variable=value
sysctl [-n] [-e] -p (default /etc/sysctl.conf)
sysctl [-n] [-e] -a
常用参数的意义:
-w 临时改变某个指定参数的值,如
sysctl -w net.ipv4.ip_forward=1
-a 显示所有的系统参数
-p 从指定的文件加载系统参数,如不指定即从/etc/sysctl.conf中加载
如果仅仅是想临时改变某个系统参数的值,可以用两种方法来实现,例如想启用IP路由转发功能:
1) # echo 1 > /proc/sys/net/ipv4/ip_forward
2) # sysctl -w net.ipv4.ip_forward=1
以上两种方法都可能立即开启路由功能,但如果系统重启,或执行了 service network restart 命令,所设置的值即会丢失!
如果想永久保留配置,可以修改/etc/sysctl.conf文件将 net.ipv4.ip_forward=0 改为net.ipv4.ip_forward=1
How to bind IP that doesn't exist yet?
# sysctl -w net.ipv4.ip_nonlocal_bind=1
# echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.conf
##############################################
# echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.conf
# sysctl -p
###############################################
# echo 1 > /proc/sys/net/ipv4/ip_nonlocal_bind
# echo "net.ipv4.ip_nonlocal_bind=1" >> /etc/sysctl.conf