dockerdesktop 制作asp.net core webapi镜像-连接sqlserver数据库容器

1.使用visual studio 创建 asp.net core webapi项目

选择启用docker 会生成Dockerfile文件

2.使用efcore连接数据库,安装efcore的包

csharp 复制代码
  <ItemGroup>
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.10" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

  </ItemGroup>

3.实体类和数据库对应

csharp 复制代码
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace WebApplication4
{
    public class Inventory
    {
        [Key]
        public int id { get; set; }

        public string name { get; set; }
        public int quantity { get; set; }
    }
}

4.配置数据库连接字符串

//Data Source用的是容器里面的数据库容器名,这里需要容器之间通讯

csharp 复制代码
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=sql-server2022;Database=TestDB;User Id=SA;Password=123456;"
  }
}

5.创建数据库上下文

csharp 复制代码
using Microsoft.EntityFrameworkCore;

namespace WebApplication4
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //optionsBuilder.UseSqlServer("server=localhost,1400;uid=SA;pwd=peng@123;database=TestDB");
        }

        public DbSet<Inventory> Inventory { get; set; }
    }
}

6.业务代码

csharp 复制代码
namespace WebApplication4
{
    public interface Iservice
    {
        void add(Inventory inventory);

        void remove(int id);

        List<Inventory> Getlsit();
    }
}
namespace WebApplication4
{
    public class service : Iservice
    {
        private readonly AppDbContext _context;

        public service(AppDbContext context)
        {
            _context = context;
        }

        public void add(Inventory inventory)
        {
            _context.Inventory.Add(inventory);
            _context.SaveChanges();
        }

        public List<Inventory> Getlsit()
        {
            return _context.Inventory.ToList();
        }

        public void remove(int id)
        {
            var ENRTY = _context.Inventory.FirstOrDefault(p => p.id == id);
            _context.Inventory.Remove(ENRTY);
            _context.SaveChanges();
        }
    }
}

7.注入服务

csharp 复制代码
using Microsoft.EntityFrameworkCore;

namespace WebApplication4
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddScoped<Iservice, service>();
            builder.Services.AddDbContext<AppDbContext>(options =>
             options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
            builder.Services.AddSwaggerGen();

            var app = builder.Build();
             //注释可以在生产环境看到swagger页面
            // Configure the HTTP request pipeline.
            //if (app.Environment.IsDevelopment())
            //{
            app.UseSwagger();
            app.UseSwaggerUI();
            //}

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }
    }
}

8.contrllor代码

csharp 复制代码
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication4.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InveryController : ControllerBase
    {
        private readonly Iservice iservice;

        public InveryController(Iservice iservice)
        {
            this.iservice = iservice;
        }

        [HttpGet]
        public IActionResult Getlist()
        {
            return new JsonResult(iservice.Getlsit());
        }

        [HttpPost]
        public IActionResult Add([FromBody] Inventory inventory)
        {
            iservice.add(inventory);
            return Ok("add success");
        }

        [HttpDelete("{id}")]
        public IActionResult delete(int id)
        {
            iservice.remove(id);
            return Ok("remove success");
        }
    }
}

9.编写dockerfile文件

根据自己的项目信息更改

csharp 复制代码
#获取asp.net6的镜像
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
#创建工作目录
WORKDIR /app
#复制当前目录到工作目录
ADD . /app
#开放端口
EXPOSE 5999
CMD ["--urls","http://0.0.0.0:5999"]
#设置环境变量
ENTRYPOINT ["dotnet", "WebApplication4.dll"]

10.发布项目

11.切换到发布文件目录 终端打开

12.添加网络(不添加容器间无法通讯)

bash 复制代码
 docker network create mynetwork
 #sql-server2022(数据库容器)
  docker network connect mynetwork   sql-server2022 

13.构建镜像

bash 复制代码
docker build -t webapplication4 -f ./Dockerfile .

13.运行容器(把容器加到添加的网络里)

-d 后台运行

--name 容器的名字

-p 端口映射

--network 网桥名称

webapplication4 镜像的名称

bash 复制代码
docker run -d  --name webapiTest -p 5999:5999 --network=mynetwork webapplication4

14.查看运气是否运行

bash 复制代码
docker ps

15.在浏览器里运行(点击进入浏览器)

在网址里加上 /swagger/index.html

就可以访问数据了。
注意:如果访问的数据库不在docker容器里面就直接写ip地址就行,如果做了端口映射,数据库连接要127.0.0.1,1434 这样的形式。

end...

相关推荐
计算机毕设定制辅导-无忧学长6 小时前
西门子 PLC 与 Modbus 集成:S7-1500 RTU/TCP 配置指南(一)
服务器·数据库·tcp/ip
程序员柳7 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
梦在深巷、7 小时前
MySQL/MariaDB数据库主从复制之基于二进制日志的方式
linux·数据库·mysql·mariadb
IT乌鸦坐飞机7 小时前
ansible部署数据库服务随机启动并创建用户和设置用户有完全权限
数据库·ansible·centos7
IT_10247 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
祁思妙想8 小时前
八股学习(三)---MySQL
数据库·学习·mysql
惊骇世俗王某人9 小时前
1.MySQL之如何定位慢查询
数据库·mysql
秦歌6669 小时前
向量数据库-Milvus快速入门
数据库·milvus
Edingbrugh.南空11 小时前
Flink SQLServer CDC 环境配置与验证
数据库·sqlserver·flink
码不停蹄的玄黓11 小时前
MySQL分布式ID冲突详解:场景、原因与解决方案
数据库·分布式·mysql·id冲突