0
votes

I'm trying to connect to a SQL Database inside a Virtual Machine hosted on Azure.

My App Service and the Virtual Machine are in different subscriptions. I've a DNS name for the VM which has also a public IP. I've added a firewall rule in the Azure VM firewall enabling 1433 port for the App Service IPs (found in Properties-->Additional Outbound IP Addresses).

In the same rule I've added my IP (with the purpose of checking if the rule was applied correctly) and I was able to connect to the database using SSMS from my PC.

I tried to publish a very simple WebJob on the App Service, just to try the connection. This is the code I'm using:

static void Main(string[] args)
        {
            using (SqlConnection connection = new SqlConnection("Server=myvirtualmachine.westeurope.cloudapp.azure.com;Database=mydatabase;User ID=myuser;Password=mypassword;MultipleActiveResultSets=False;Connection Timeout=60;TrustServerCertificate=False;Persist Security Info=False"))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("SELECT * FROM myTable", connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                Console.WriteLine(reader.GetValue(i));
                            }
                            Console.WriteLine();
                        }
                    }
                }
            }
        }

If I run this WebJob I receive the error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server.

Is a VNET or a Hybrid Connection mandatory to connect an Azure App Service to a SQL Database on Azure Virtual Machine or is it possible in other ways?

1

1 Answers

1
votes

Yes you need to use a VNET or enable Public IP to have the connectivity with the Appservice from your SQL inside a VM.

You an read more here