The personal ramblings of Jon Carlos mobile & web developer and technology enthusiast.

Saturday, 25 April 2015

Using docker containers to run .net site on linux more complex example

22:19 Posted by Webmonger , , , , 12 comments
 Image by Greg Bishop used under creative commons licence

Because of the work I do with Xamarin I'm quite used to working on a mac but building using .net and C#. Amongst .net developers this is quite unusual however this is about to change with the recent open sourcing of the framework and Roslyn compiler there will be the ability to run .net on any platform.

This led me to start to investigate how you go about building and deploying applications on Linux. With Xamarin and mono this has been possible for some time though I don't think this is used quite to the extent developers use it for building mobile applications.

I guess the first thing I'd like to say about this process is that I found the set-up relatively easy but the complexity of the example apps I could find were really low so I started to hunt for something more complex so I could really get an idea of how .net ran within a Docker container on ubuntu.

Most of the docker commands are available on this MSDN article "Running ASP.NET 5 applications in Linux Containers with Docker" and a bit more detail about what you're actually doing is also available there. I'm going to concentrate on a couple of things, first I had quite a few issues getting boot2docker to allow me to access containers on my mac, secondly when building containers with boot2docker I had some issues with downloading NuGet packages.

  1. Get docker installed on your local machine or on an ubuntu box, there are loads of posts on how to do this but the docker site probably covers it best and most comprehensively for all platforms.
  2. Make sure git in installed on the host machine as we'll be cloning a repository that contains the app for our container.
  3. If you are running boot2docker all the following commands should work on your mac host or by working directly on a Linux box, if you're working on a Linux VM you'll need to SSH on to the box to run the following.
Getting the Application
As I said before the complexity of the projects that were used in most .net + docker examples was very low. After a little research I found the Music Store project which is a store front for CD purchases, it has a little bit of database logic and a few pages as well as login functionality and shopping cart.

To download this repository run

git clone

I found when building the container for this code it could not find all the NuGet packages so use a text editor to create a NuGet.config in the MusicStore project folder.

In Lunix or on a mac run

cd MusicStore/src/MusicStore

nano NuGet.config 

Paste this code in to the file

Once finished (when using nano) press ctrl+x then y then press [enter]

Building your container
To build a container you need to create a script that will tell docker how to configure the container  to run you app.

This script is called a Dockerfile create us file by running

nano Dockerfile

Now we need to add the build configuration so paste this code in to the file then press ctrl+x then y then press [enter] to save and exit nano.

FROM microsoft/aspnet

COPY . /app
RUN ["kpm", "restore"]

ENTRYPOINT ["k", "kestrel"]

I'm not going to go in too too much detail about what these commands do but the 2 main ones that will become more familiar with you once vNext comes out is "kpm restore" which will restore all the packages required for the project and "k kestrel" which is a basic web server that is capable of running sites.

Next we want to build our container. At the beginning of this article I explained the different ways you can set-up docker, some times you'll need to add sudo to the front of the following commands. In my set-up they work fine without.

docker build -t musicstore .

This command will then go off and run all the commands in your Dockerfile depending on how fast you connection and machine are it might take a little while as it's downloading the microsoft/aspnet docker container and all the NuGet libraries as well.

Once that's complete you should have a new image listed in your docker image repository, to see if it's there run

docker images

You should see an image called musicstore in the list, this is the container we're now going to start. Just run

docker run -t -d -p 80:5004 musicstore

I ran in to quite a few issues with this however when I ran this command on my ubuntu server it worked perfectly every time. If you are running this within an ubuntu VM you will need to configure the NAT settings on the VM for port forwarding, I also had issues using port 80 and 8080 in this configurations so I tried using NAT to transfer port 8081 to port 80 and it worked perfectly so just play about with the following settings if you have problems.

You can find this screen in VirtualBox by right clicking on your VM selecting Settings > Network > Port forwarding (down at the bottom) then clicking the add button on the right.

Now open up the browser of your choice and with any luck hit the IP address of your server/VM/boot2docker/localhost with or without the additional port number and you should see something like this.

So I hope you'll agree, with reasonably little effort you've just managed to set-up quite a complex .net app on a docker container with little work.

I'm sure if you're a .net developer you can see how this might revolutionise the way you deploy apps in to the wild or even just develop locally on your many work machines or between multiple developers! I have managed to get this docker set-up to work across Windows, Linux and OS X which is pretty cool and the ability to scale the number of instances running your app with just that simple command is amazing.

I hope you managed to have a bit of fun with this and if you have any questions let me know.


Anonymous said...

great tutorial!
but unfortunately when i try to build the Dockerfile, i get:
INFO[0001] [8] System error: exec: "kpm": executable file not found in $PATH

Webmonger said...

It sounds like you might not be using the latest version of the aspnet image or you're using a different image. The docker instance should have that configured if I remember correctly.

praveen said...

Wow i amazed with your blog,
Thanks to share with us,
web designing training in chennai

web designing training in porur

digital marketing training in chennai

digital marketing training in porur

rpa training in chennai

rpa training in porur

tally training in chennai

tally training in porur

hrithiksai said...

Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data sciecne course in hyderabad

Anonymous said...

Номенклатура деяний, направленных на предвидение жизненного пути, называется гадание. Гадание онлайн на будущее с мужчиной - это простой вариант поворожить с использованием всяких предметов и средств. Сверхъестественные силы и разного рода обстоятельства предсказания судьбы наукой не доказаны, однако многие люди доверяют такому.

Priyanka said...

Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
Data Analyst Course

Anonymous said...

Керамику pamesa castle производят только из естественных компонентов. Экологичный материал, практически безопасен для проживающих. Её возможно применять в залах заведений столовых, в школах и детских садиках.

Anonymous said...

Занять требуемую сумму на карточку более чем просто. Онлайн сайт выбора финансовых продуктов разрешает взять необходимый микрокредит. Мигкредит – это оптимальный вариант достать деньги в сжатые сроки.

Anonymous said...

Всякий хочет знать свою судьбу и воспринимает конкретные средства хиромантии гораздо больше действенными. Гадание на таро определение магических способностей это вариант увидеть предстоящие явления непрерывно манил род человеческий. Хиромантия позволяет предположить, что человека подстерегает в ближайшем времени.

Anonymous said...

Пройдите регистрацию на платформе и получайте нужные бонусы в своей учетке. Вспомогательный счет даст возможность загрести больше денежных средств. Нужно отметить, что проект казино икс casino x зеркало на официальный дарит всем игрокам приятные бонусы.

Anonymous said...

Помните, что casino x приложение андроид ни при каких условиях не возьмет перевод за проведение процесса верификации игроков. Проверить истинность сайта реально на центральной странице Техническая служба в любой момент придет на помощь и с легкостью решит самую непростую задачу.

Anonymous said...

Собственно на странице мр бит официальный сайт посетители легко загрузят интересную интернет-игру для развлечений. Заходя в интерактивный клуб, вы имеете возможность окунуться в невероятные авантюры. Играть с единомышленниками в значительной степени интереснее, чем самому на хате.