Question

How to connect a website from VPS 1 to Database on VPS 2

Posted February 12, 2021 154 views
CentOSDatabases

I want to ask that is there any way I can connect 1 VPS containing my website to another VPS running the database or not? Anyone who has a specific tutorial to design it on MariaDB please help me, I appreciate it.

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
1 answer

Hi @vin2164382,

Yes, it’s possible to connect this. It’s actually a really common way of structuring your servers. You have one server for your Web Requests and another for your Database.

The first and most important thing you need to do is allow access for VPS 1 on VPS 2(where your database is) on the port your database is listening on. Usually, MySQL/MariaDB use the port 3306.

To allow incoming MySQL connections from a specific IP address or subnet, specify the source. For example, if you want to allow the entire 15.15.15.0/24 subnet, run these commands:

sudo iptables -A INPUT -p tcp -s 15.15.15.0/24 --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT

The second command, which allows the outgoing traffic of established MySQL connections, is only necessary if the OUTPUT policy is not set to ACCEPT.

You’ll need to change the 15.15.15.0/24 with your actual IP address and run the above commands on the Database server.

Next, when you are with this, you should be able to connect with your credentials in your website to the database.

Regards,
KFSys

  • How about If I turned off, and disable iptables, so I have to turn them on and add any port I want to access in my server, Is that right?
    And one more thing is the Ip in the command you gave me this is the ip of the vps has database, or the ip from the vps of the website.

    • You always need to have a firewall on and IPtables is that, a firewall otherwise you’ll be vulnerable to attacks.

      Otherwise, yes. That’s what the idea is behind. You deny everything and then add certain ports and IP address you wish to have access to your droplet.

    • The first command with the IP address should be run on your database server:

      sudo iptables -A INPUT -p tcp -s 15.15.15.0/24 --dport 3306 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
      sudo iptables -A OUTPUT -p tcp --sport 3306 -m conntrack --ctstate ESTABLISHED -j ACCEPT
      

      You just need to change the IP address with the IP address of your gameserver.