23 avr. 2018

Deploy an app from Gitlab's registry to Heroku (.Net Core example)


I had my ups and downs with Docker. For me, it's a great tool with pros and cons but, as I mainly use Windows for my dev. environments, making it works on the Microsoft OS can be painful.

That’s why I delegate! It's easy to find a way to make a Docker container on someone else's machine. And because I love Heroku and it’s so convenient to push a container directly to your app, I picked Gitlab (that I love too) to Dockerize my app.

The Goal

  • Dockerize an app and keep it on your Gitlab Registry (reusable at will)
  • Use the image to deploy on Heroku

Requirements

Let’s Start

  • Create a simple web API in a TestApp folder
dotnet new webapi
git init
git add .
git commit -m “First Commit”
  • Create a new repo on Gitlab and copy the address (something like git@gitlab.com:****/****.git) to add it to your local repo
git remote add origin git@gitlab.com:****/****.git
  • Add a Dockerfile in your folder (change the name of the app if needed)
FROM microsoft/aspnetcore-build:2.0 AS build-env
WORKDIR /app 

# Copy everything and build
COPY . ./
# You can point directly at your csproj file, specially if it's on a sub-folder
# On some .Net Core projects (MVC, usually) if you don't add --runtime linux-x64, it won't publish. See note (1)
RUN dotnet publish -c Release -o out *.csproj --runtime linux-x64 

# Build runtime image
FROM microsoft/aspnetcore:2.0
WORKDIR /app
COPY --from=build-env /app/out . 

# Change the name of the app here if needed (TestApp)
CMD ASPNETCORE_URLS=http://*:$PORT dotnet TestApp.dll
  • Add a .dockerignore with
bin\
obj\
  • Add a .gitlab-ci.yml file and change the information as required
https://gist.github.com/Wanchai/614bce96547655318911e039aa55271a
  • Commit everything and push
You can go to Gitlab, on your repo page, under CI / CD > Jobs and check that everything is working fine. To do this job, Gitlab is using a Shared Runner. It’s a service that will grab your .gitlab-ci.yml file and do what it says  (more here).

That’s it! Everytime you push to your repo, you will create a new Docker image and push it to Heroku.
You can pick the branch you want to deploy on the “only” part of your gitlab-ci file.

Notes

There are many issues with precompiled Views. As of today, it’s not really solved: https://www.google.fr/search?q=net+core+razor+views+precompile&oq=net+core+razor+views+precompile