[英]Dockerize an ASP.NET Core Web App with MySQL persisting Database as two separate containers with docker-compose
I have some issues trying to dockerize the web app I have written(ResumePostingService).我在尝试对我编写的 Web 应用程序 (ResumePostingService) 进行 dockerize 时遇到了一些问题。 I have a Dockerfile for my application and one for my database as well as an Init sql file to create the database some tables and insert some data.我有一个用于我的应用程序的 Dockerfile 和一个用于我的数据库以及一个 Init sql 文件来创建数据库一些表并插入一些数据。 I also have a docker-compose file.我也有一个 docker-compose 文件。 I have watched quite a few tutorials on the subject but every time I see something different and I get a different kind of error.我看过很多关于这个主题的教程,但每次我看到不同的东西时都会遇到不同类型的错误。
The latest error I am getting after the docker-compose up command when I go to localhost:8080 on my browser is the following:当我在浏览器上访问 localhost:8080 时,我在执行 docker-compose up 命令后得到的最新错误如下:
InvalidOperationException: Unable to resolve service for type 'ResumePostingService.Models.ResumePostingServiceDatabaseContext' while attempting to activate 'ResumePostingService.Pages.LoginModel'. InvalidOperationException:尝试激活“ResumePostingService.Pages.LoginModel”时,无法解析“ResumePostingService.Models.ResumePostingServiceDatabaseContext”类型的服务。
Can anyone help me on what I am doing wrong?任何人都可以帮助我解决我做错了什么吗?
Dockerfile(app) Dockerfile(应用程序)
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "ResumePostingService.dll"]
docker-compose.yml docker-compose.yml
version: '3.8'
services:
db:
build: ./Db
volumes:
- data-volume:/var/lib/db
app:
build:
context: .
dockerfile: Dockerfile
ports:
- '8080:80'
depends_on:
- db
volumes:
data-volume:
Dockerfile(db) Dockerfile(db)
FROM mysql:8.0.21
COPY *.sql /docker-entrypoint-initdb.d
ENV MYSQL_ROOT_PASSWORD myEpicPass
EXPOSE 3306
My connection string on the appsettings.json file我在 appsettings.json 文件上的连接字符串
"Default": "server=127.0. 0.1;user=root;password=myEpicPass;port=3306;database=ResumePostingServiceDB"
The command I use to connect to the db inside Startup.cs我用来连接到 Startup.cs 中的数据库的命令
services.AddTransient(_ => new MySqlConnection(Configuration["ConnectionStrings:Default"]));
You need to change 127.0.0.1 to the service name (like in compose file), in your case it's db , so the connection string should look like this:您需要将 127.0.0.1 更改为服务名称(如在撰写文件中),在您的情况下是db ,因此连接字符串应如下所示:
"Default": "server=db;user=root;password=myEpicPass;port=3306;database=ResumePostingServiceDB"
More information about networking in docker-compose: https://docs.docker.com/compose/networking/有关 docker-compose 网络的更多信息: https : //docs.docker.com/compose/networking/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.