1. 程式人生 > >Docker 之web api 訪問 host sql server

Docker 之web api 訪問 host sql server

執行 Docker

C:\Users\Administrator>docker run -it  -p 5000:5000 --name myapidocker1 webapiv1

 

[email protected]:/# dir

bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  test  tmp  usr  var

 

 

C:\Users\Administrator>docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES

3b3e97bb6e21        webapiv1            "bash"              9 seconds ago       Up 8 seconds        0.0.0.0:5000->5000/tcp   myapidocker1

 

deploy 編譯後的dll,編譯選項選擇如下

 

 

 

D:\Work\My\opensource\Dotnet2\WebAPIForDocker\bin\Debug>docker cp netcoreapp2.1/publish myapidocker1:/test/api3

 

檢視配置,注意linux sqlserver 埠號必須指定

 

[email protected]:/test/api3/publish# cat appsettings.json

{

  "Logging": {

    "LogLevel": {

      "Default": "Information"

    }

  },

  "AllowedHosts": "*",

  "ConnectionStrings": {

    "DefaultConnection": "Max Pool Size = 51200;Server=localhost,1433;User ID=sa;Pwd=XXXXX;DataBase=Order;"

  }

}

 

進入到容器

 

如果不小心關閉了,docker 的終端,再次進入docker

 

C:\Users\Administrator>docker exec -it myapidocker1 /bin/bash

[email protected]:/# dir

bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  test  tmp  usr  var

 

 

執行 core

[email protected]:/test/api3/publish# dotnet WebAPIForDocker.dll

 

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]

      User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.

Hosting environment: Production

Content root path: /test/api3/publish

Now listening on: http://[::]:5000

Application started. Press Ctrl+C to shut down.

 

 

開啟另一個終端,在docker 內部訪問

 

[email protected]:/# curl http://localhost:5000/api/orders/getHostName

[email protected]:/

 

[email protected]:/# curl http://localhost:5000/api/orders/getOrderList

[{"item1":"ja201808204778560863744992601","item2":"08/20/2018 18:29:16"},{"item1":"201808205628636382300589946","item2":"08/20/2018 18:29:18"},{"item1":"201808205753427170575780018","item2":"08/20/2018 18:29:19"},{"item1":"201808204749312987745111125","item2":"08/20/2018 18:29:21"},{"item1":"201808204725778270582113008","item2":"08/20/2018 18:29:22"},{"item1":"201808204776350327734840932","item2":"08/20/2018 18:29:27"},{"item1":"201808205627318305959441050","item2":"08/20/2018 18:29:30"},{"item1":"201808205593544898683339668","item2":"08/20/2018 18:29:34"},{"item1":"201808205707984438836626731","item2":"08/20/2018 18:29:35"},{"item1":"201808205573431454844603206","item2":"08/20/2018 18:29:39"}][email protected]:/#

 

 

webAPI部分程式碼:

 

[Route("api/[controller]")]

    public class OrdersController : Controller

    {

        private IConfigOptions m_configOptions;

        private ILogger m_logger;

        public OrdersController(IConfigOptions configOptions, ILogger<OrdersController> logger)

        {

            m_configOptions = configOptions;

            m_logger = logger;

        }

        // GET api/values

        [Route("[action]")]

        [HttpGet]

        public ActionResult<IEnumerable<Tuple<string, string>>> GetOrderList()

        {

            m_logger.LogDebug(" ConnectionString:" + m_configOptions.ConnectionString);

            //Console.WriteLine(" ConnectionString:" + m_configOptions.ConnectionString);

            List<Tuple<string, string>> list = new List<Tuple<string, string>>();

            try

            {

                using (SqlConnection sqlCon = new SqlConnection(m_configOptions.ConnectionString))

                {

 

                    sqlCon.Open();

                    string sql = "select top 10 * from [dbo].[Order]";

 

                    using (SqlCommand cmd = new SqlCommand(sql, sqlCon))

                    {

                        var reader = cmd.ExecuteReader();

                        while (reader.Read())

                        {

                            list.Add(new Tuple<string, string>(reader["orderNum"].ToString(), reader["InDate"].ToString()));

                        }

                    }

                }

            }

            catch(Exception ex)

            {

                m_logger.LogError(ex, ex.Message, "Get");

            }

 

            return list;

        }

 

        // GET api/values/5

        [Route("[action]")]

        [HttpGet]

        public ActionResult<string> GetHostName()

        {

            string hostName = Dns.GetHostName();

            return hostName;

        }

 

       

    }

 

webAPI部分程式碼: