Connect to SQL Server database from a docker container

前端 未结 3 544
不知归路
不知归路 2021-02-01 06:49

I have docker for windows installed on my machine. There is a console application targeting .net core 1.0.0 that tries to access a SQL Server database running on a different VM.

3条回答
  •  天涯浪人
    2021-02-01 07:24

    Assumptions

    • Microsoft SQL Server 2016
    • Windows 10 Anniversary Update
    • Windows Containers
    • ASP.NET Core application

    Add a SQL user to your SQL database.

    • In MS SQL expand the database
    • Right click on 'Security / Logins'
    • Select 'New Login'
    • Create a user name and password.
    • Assign a 'Server Role(s)'...I used sysadmin since I'm just testing
    • Under 'User Mapping' I added my new user to my database and used 'dbo' for schema.

    Change SQL Authentication to allow SQL Server Authentication Mode

    Right click on your database, select 'Properties / Security / Server Authentication / SQL Server and Windows Authentication Mode' radio button. Restart the MS SQL service.

    Update your appsettings.json with your new user name and password

    Example

    "ConnectionStrings": {
            "DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;MultipleActiveResultSets=true;User Id=UserNameYouJustAdded;Password=PassordYouJustCreated"
    },
    

    Make sure you remove Trusted_Connection=True.

    Create a Docker file

    My example Docker file

    FROM microsoft/dotnet:nanoserver
    ARG source=.
    WORKDIR /app 
    EXPOSE 5000 
    EXPOSE 1433 
    ENV ASPNETCORE_URLS http://+:5000 
    COPY $source .
    

    Publish Application

    Running from the same location as the Docker file in an elevated PowerShell

    dotnet publish
    
    docker build bin\Debug\netcoreapp1.0\publish -t aspidserver
    
    docker run -it  aspidserver cmd
    

    I wanted to run the container and see the output as it was running in PowerShell.

    Once the container was up and running in the container at the command prompt I kicked off my application.

    dotnet nameOfApplication.dll
    

    If everything went to plan one should be up and running.

提交回复
热议问题