Mysql building container
1, the mirror pulling mysql
docker pull mysql/mysql-server
2, create mirrored 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_ci
3, enter mysql licensed to the user above "lzl" permission
①docker exec -it mysql01 bash
②mysql -uroot -p
③GRANT ALL PRIVILEGES ON . TO 'LZL'@'%' WITH GRANT OPTION;
Construction of .NetCoreApi
First, the new api project
Second, the installation drive mysql
MySql.Data.EntityFrameworkCore 8.0.18 connection .netCore3.0 there Bug, when failure to do Db migration. Therefore the use of Pomelo.EntityFrameworkCore.MySql drive.
Microsoft.EntityFrameworkCore.tools。
Third, the new Model, configure DbContext
① New Folder Entityes, New 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; }
}
}
② New Folder Data, New UserContext.cs
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; }
}
}
Fourth, configure UserContext DI injection, configure MYSQL connection strings
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;"
}
Note: Server = mysql01 here is the name of the first step Mysql container. When the local development server can be set to Db corresponding to the address.
V. initialization Db
In turn execute Add-Migration IntialDb, Update-Database
Six, adding SeedData
StartUp.cs add the following code to initialize the data.
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();
}
}
}
Seven new 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);
}
}
}
Eight, to start the project, test the connection is successful
Nine, Dockerfile preparation of the api
# 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"]
10, cmd to enter the dos directory of the project to construct a mirror api
docker build -t userapi:prod .
-T directory where the image name dockerfile
11, create a Network, and for connecting the container mysql container api
docker network create -d bridge my-network
-d
Docker parameter specifies the network type, there is bridge
overlay
. Wherein overlay
the network type for Swarm mode
12, create a startup api container, specify the corresponding network
docker run -d -p 8084:3827 --network my-net --name myuserapi userapi:prod
Local port 8084, listening port container 3827
13, since mysql01 added to the vessel and no network connection, api container remains inaccessible. The following mysql01 added to the my-net to
docker network connect my-net mysql01 #添加进网络
docker network disconnect my-net mysql01 #从网络中移除
14, to see whether the two containers in the same network segment.
docker inspect myuserapi
docker inspect mysql01