Apply Entity Framework migrations when using ASP.Net Core in a Docker image Apply Entity Framework migrations when using ASP.Net Core in a Docker image docker docker

Apply Entity Framework migrations when using ASP.Net Core in a Docker image


Regardless of your deployment type, you can Apply migrations at runtime on your Startup class at the very end of your Configure method, e.g. calling the following method:

public void ApplyMigrations(ApplicationDbContext context) {    if (context.Database.GetPendingMigrations().Any()) {        context.Database.Migrate();    }}


A couple of things:

1) A RUN command in a Dockerfile is an instruction executed during the build of the container image - so it will run once (and probably fail because there's no database) where you are building the image rather than when you later run the image.

2) I would recommend separating performing migrations from the deployment of a new version of your container. You may only be running a single copy of the container at the moment, but if you ever ran 2 or more then you would have multiple containers all checking to see if they should run migrations and that could cause issues.There's also the problem that you have deployed code that depends upon the migration, but you don't yet know that the migration will work - better to run the migrations first, and if they fail, don't deploy the new container.