Create a Linked Server Between Two Docker Containers running SQL Server (T-SQL Example)

This article walks through the process of creating a linked server from a SQL Server instance on one Docker container, to a SQL Server instance on another Docker container. Both Docker containers are on the same machine.

The process is exactly the same that you would use to create any linked server (for example, even if the SQL Server instances were on separate machines and not running in a Docker container).

All examples here use Transact-SQL. This enables you to create the linked server without relying on a graphical user interface (such as SSMS).

Create the Linked Server

To create a linked server using T-SQL, execute the sp_addlinkedserver stored procedure while passing in the name of the linked server as well as its source.

Here’s an example of creating a linked server:

EXEC sp_addlinkedserver 
    @server=N'Homer', 
    @srvproduct=N'', 
    @provider=N'MSOLEDBSQL', 
    @datasrc=N'172.17.0.2,1433';

In this case, the linked server name is Homer and I specify the IP address of the Docker container, followed by the TCP port. Change the server name and IP address/port as required.

You can find the IP address of your Docker container by running the following code in a terminal window:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' Homer

If that doesn’t work, try the older method:

docker inspect -f"{{.NetworkSettings.IPAddress}}" Homer

Change the container name as required.

Test the Linked Server

Now that you’ve added the linked server, you can use sp_testlinkedserver to test it:

EXEC sp_testlinkedserver Homer;

Result (if successful):

Commands completed successfully.

Login Failed?

If you get a “Login failed” error, chances are you don’t have a corresponding login on the remote server. You’ll need to have a corresponding login with the same credentials as the one on the local server.

Alternatively, you could create a separate login just for the linked server.

See Create a Linked Server in SQL Server (T-SQL Example) for more details and examples of doing this. That article uses the same details for the linked server as the ones in this article. It also has an example of running a distributed query and a pass-through query on the linked server once it has been configured.

Drop a Linked Server

Here’s an example of dropping the linked server called “Homer” and all associated logins.

EXEC sp_dropserver 'Homer', 'droplogins';

The droplogins argument is optional, but if you don’t specify this when dropping a linked server that has associated remote and linked server login entries, or is configured as a replication publisher, an error message is returned.

See Remove a Linked Server using T-SQL for more examples.