.NetCoreApi容器與MySql容器互聯

構建Mysql容器

一、拉取mysql鏡像

docker pull mysql/mysql-servermysql

二、建立mysql鏡像

docker run -d -p 3306:3306 -e MYSQL_USER="lzl" -e MYSQL_PASSWORD="password" -e MYSQL_ROOT_PASSWORD="password" --name mysql01 mysql/mysql-server --character-set-server=utf8 --collation-server=utf8_general_cigit

三、進入mysql 受權給上面用戶"lzl"權限

①docker exec -it mysql01 bashsql

②mysql -uroot -pdocker

③GRANT ALL PRIVILEGES ON . TO 'LZL'@'%' WITH GRANT OPTION;json

構建.NetCoreApi

1、新建api項目

image-20200105103151900

2、安裝mysql驅動

MySql.Data.EntityFrameworkCore 8.0.18鏈接.netCore3.0 有Bug ,作Db遷移的時候失敗.所以採用Pomelo.EntityFrameworkCore.MySql驅動。c#

Microsoft.EntityFrameworkCore.tools。api

image-20200105103321440

3、新建Model、配置DbContext

①新建文件夾Entityes、新建User瀏覽器

namespace Api.Entities
{
    public class User
    {
        public int Id { get; set; }

        public string Name { get; set; }
    
        public string Company { get; set; }
    
        public string Title { get; set; }
    }

}

②新建文件夾Data、新建UserContext.csbash

namespace Api.Data
{
    public class UserContext:DbContext
    {
        public UserContext(DbContextOptions<UserContext> options):base(options)
        {

        }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<User>()
            .ToTable("t_ApiUser");
        }
    
        public DbSet<User> Users { get; set; }
    }

}

4、配置UserContext DI注入、配置MYSQL連接字符串

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<UserContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("MySqlConString"));
            });
            services.AddControllers();
        }
"ConnectionStrings": {
    "MySqlConString":            "Server=mysql01;database=db_appuser;userid=lzl;password=password;"
  }

注意:此處Server=mysql01爲第一步Mysql容器的名稱。在本地開發的時候能夠設置爲對應的Db服務器地址。服務器

5、初始化Db

依次執行 Add-Migration IntialDb、Update-Database

image-20200105105337799

6、添加SeedData

StartUp.cs添加如下代碼初始化數據。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
     {
        if (env.IsDevelopment())
        {
          app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        InitialDataBase(app);
    }

    public void InitialDataBase(IApplicationBuilder app)
    {
        using (var scope = app.ApplicationServices.CreateScope())
        {
            var context = scope.ServiceProvider.GetRequiredService<UserContext>();

            if (!context.Users.Any())
            {
                context.Users.Add(new User()
                {
                    Company = "kingdee",
                    Name = "LZL",
                    Title = "2020",
                    Id = 1
                });
                context.SaveChanges();
            }
        }
    }

7、新建UserController

namespace Api.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class UserController : ControllerBase
    {
        private ILogger<UserController> _logger;
        private UserContext _userContext;
        public UserController(ILogger<UserController> logger,UserContext userContext)
        {
            _logger = logger;
            _userContext = userContext;
        }

        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var users = await _userContext.Users.ToListAsync();
            return new JsonResult(users);
        }
    }

}

8、啓動項目,測試鏈接是否成功

image-20200105110437253

9、編寫api的Dockerfile

# 1.指定編譯和發佈應用的鏡像

FROM mcr.microsoft.com/dotnet/core/sdk:3.0 AS build-env

# 2. 指定(編譯和發佈)工做目錄

WORKDIR /app

# 3. 拷貝.csproj到工做目錄/app,而後執行dotnet restore恢復全部安裝的NuGet包

COPY *.csproj ./
RUN dotnet restore

# 4. 拷貝當前項目目錄下全部文件到工做目錄(/app),而後執行dotnet publish命令將應用發佈到/app/out目錄下

COPY . ./
RUN dotnet publish -c Release -o out

# 5. 編譯生成Docker鏡像

# 5.1.設置基礎鏡像

FROM mcr.microsoft.com/dotnet/core/aspnet:3.0 AS runtime

# 5.2. 設置(運行)工做目錄,並將發佈文件拷貝到out子目錄下

WORKDIR /app
COPY --from=build-env /app/out .

# 5.3. 利用環境變量設置ASP.NET Core應用的監聽地址

ENV ASPNETCORE_URLS http://0.0.0.0:3827

# 5.4. 執行dotnet命令啓動ASP.NET Core應用

ENTRYPOINT ["dotnet", "Api.dll"]

十、cmd進入項目的dos目錄、構建api鏡像

docker build -t userapi:prod .

-t 鏡像名稱 dockerfile所在的目錄

image-20200105111250017

十一、建立network,用於鏈接mysql容器和api容器

docker network create -d bridge my-network

-d 參數指定 Docker 網絡類型,有 bridge overlay。其中 overlay 網絡類型用於 Swarm mode

十二、建立啓動api容器,指定對應的network

docker run -d -p 8084:3827 --network my-net --name myuserapi userapi:prod

本機端口8084,容器監聽端口3827

1三、因爲mysql01容器並無加入到該網絡鏈接,api容器依然沒法訪問。下面將mysql01添加到my-net中來

docker network connect my-net mysql01  #添加進網絡

docker network disconnect my-net mysql01 #從網絡中移除

1四、查看兩個容器是否在同一網段

docker inspect myuserapi

image-20200105113954007

docker inspect mysql01

image-20200105114103427

1五、瀏覽器訪問localhost:8084/User/Get。

image-20200105113559841

docker中netcoreapi鏈接Mysql成功

相關文章
相關標籤/搜索