<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Likhit Dharmapuri on Medium]]></title>
        <description><![CDATA[Stories by Likhit Dharmapuri on Medium]]></description>
        <link>https://medium.com/@Likhitd?source=rss-390a13b6896a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Oaj7YLk12dXCac6C-suZWw.jpeg</url>
            <title>Stories by Likhit Dharmapuri on Medium</title>
            <link>https://medium.com/@Likhitd?source=rss-390a13b6896a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:55:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Likhitd/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ASP.NET core and MySQL with Docker — Part 3]]></title>
            <link>https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-3-e3827e006e3?source=rss-390a13b6896a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3827e006e3</guid>
            <category><![CDATA[entity-framework]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Likhit Dharmapuri]]></dc:creator>
            <pubDate>Sat, 07 Oct 2017 21:35:14 GMT</pubDate>
            <atom:updated>2017-10-07T21:35:14.260Z</atom:updated>
            <content:encoded><![CDATA[<h4>Connecting the web service container to a MySQL container</h4><p>This article is the final part of a series of 3 posts:</p><ol><li><a href="https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-1-b7ef538ecd8e">Creating and containerizing the web API using a in memory db</a></li><li><a href="https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-2-ee7fba1fc508">Building the code inside a container and using docker compose</a></li><li>Connecting the web service to a MySQL container (this)</li></ol><p>The full code can be found <a href="https://github.com/Likhit/Docker-With-ASP-Core-and-MySQL">here</a>.</p><p>In the previous posts we created a ASP.NET core Web API using an in-memory database. We then learnt how to build and run the solution on docker and docker-compose. In this post we will finally create a MySQL container with persistent storage, and link the web API container to use it.</p><h3>Starting a MySQL container</h3><p>The official MySQL container is available on <a href="https://hub.docker.com/r/mysql/mysql-server/">docker hub</a>. We will use the stable version 5.7. To start a simple instance of the container run:</p><pre>&gt; docker run --name db -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql/mysql-server:5.7</pre><p>We can connect to the container and run the mysql client using:</p><pre>&gt; docker exec -it db mysql -u root -p<br>Enter password: my-secret-pw<br>mysql&gt; show databases;</pre><h4>MySQL environment variables</h4><p>The MySQL image takes a number of environment variables. They are all described in the <a href="https://hub.docker.com/r/mysql/mysql-server/">docker hub</a> page. Here we’ll explore some of them:</p><ol><li>MYSQL_ROOT_PASSWORD is used to set the root password for mysql server. The root user has access to all databases on the server, and can create/modify new databases. Passing passwords in terminal is insecure, and therefore this option should be avoided for non-toy applications.</li><li>MYSQL_RANDOM_ROOT_PASSWORD asks the container to create a random root password for the server. You can read the generated password by looking at the container logs using docker logs &lt;container-name&gt;. We will be using this option in the future.</li><li>MYSQL_ROOT_HOST is used to specify the IP address of the root user. The container, by default, does not allow anyone to log into the server as root from outside the container. This prevents other containers (or the host too) from connecting to the db (using root credentials). You can use this flag to pass the IP of the container or host which should be allowed to connect to the server with root credentials. Eg. To allow the host to connect, you would set -e MYSQL_ROOT_HOST=&quot;172.17.0.1&quot;.</li><li>MYSQL_DATABASE creates a database on the server on container startup.</li><li>MYSQL_USER, MYSQL_PASSWORD are used to create a new user (not root) with super user privileges over MYSQL_DATABASE. Note that unlike root, these new user credentials can be used to connect to the db from outside the container too.</li></ol><p>We will not connect to the MySQL container (from our web service container) using root privileges. This is because in order connect using root privileges we will need to start the MySQL container with -e MYSQL_ROOT_HOST=&lt;container_IP&gt;. This creates an ugly dependency loop:</p><ul><li>The MySQL container depends on the web service container for its IP address.</li><li>The web service container depends on the MySQL container to connect to the db.</li></ul><p>This creates a problem. Which container starts first? There are ways to make this work, but that would involve ugly hacks. Instead we will use MYSQL_USER credentials to connect to our db container. This obviously requires us to specify MYSQL_DATABASE too.</p><h4>Persistent storage</h4><p>A container encapsulates its own file system. Therefore, when the container is destroyed, we will lose all db data. To persist data we will need to use a docker managed volume and map it to /var/lib/mysql — the default location where MySQL server stores db data. The MySQL container will create a docker volume if none is specified, but it will be better to pass our own named volume.</p><p>Finally, lets start a proper mysql container to use with our web service.</p><pre># Stop and remove the container created previously.<br>&gt; docker stop db; docker rm db;</pre><pre># Create a db volume<br>&gt; docker volume create dbvol</pre><pre># Start the container<br># Let us also forward the MySQL server port 3306 to the host so that the host can connect using MYSQL_USER credentials to the db from localhost:3306.<br>&gt; docker run --name db -e MYSQL_RANDOM_ROOT_PASSWORD=yes -e MYSQL_DATABASE=Students -e MYSQL_USER=user_name_1 -e MYSQL_PASSWORD=my-secret-pw -v dbvol:/var/lib/mysql -p 3306:3306-d mysql/mysql-server:5.7</pre><h3>Configuring the Web API</h3><p>In order to now connect to the MySQL db, we will need to change our ASP.NET application code. First, we will need to install Entity Framework provider for MySQL. We will be using the <a href="https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql">Pomelo Foundation provider</a> — at the time of writing this article, the official MySQL doesn’t work with ASP.NET core 2.0.</p><pre># Install the EF provider<br>&gt; dotnet add package Pomelo.EntityFrameworkCore.MySql --version 2.0.0</pre><h4>Creating EF migrations</h4><p>In order to create the initial db, we need to create an EF migration for our DB schema. In order to create migrations we need to install the entity framework dotnet cli packages. Unfortunately, we can’t install them directly through the command line.</p><p>Add the following ItemGroup to your .csproj:</p><pre>&lt;ItemGroup&gt;<br>    &lt;DotNetCliToolReference Include=&quot;Microsoft.EntityFrameworkCore.Tools&quot; Version=&quot;2.0.0&quot; /&gt;<br>    &lt;DotNetCliToolReference Include=&quot;Microsoft.EntityFrameworkCore.Tools.DotNet&quot; Version=&quot;2.0.0&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>Now run dotnet restore to install the required packages. To create a migration, we need to be connected to the db. Our web app is currently configured to connect to an in-memory db. Modify Startup.cs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c69f7e106f414b1013ded7dcc12f82c0/href">https://medium.com/media/c69f7e106f414b1013ded7dcc12f82c0/href</a></iframe><p>Using the Pomelo provider we are connecting from the host to the MySQL container db. Notice that the Configure function has a new context.Database.Migrate() call. This ensures that when the application is started, the connected db has all the required tables and migrations applied.</p><p>Create a migration using dotnet ef migrations add Initial. This creates a migration named Initial. context.Database.Migrate will apply this migration when we run the app and create the initial tables in the empty database.</p><h4>Running the web service</h4><p>Docker allows us to connect two containers using the --link option with docker run. Eg:</p><pre>&gt; docker run --name mybash --link db -it bash</pre><p>This links the db container to the mybash container. When a container A is linked to container B, all the environment variables declared in A are exported to B, all exposed ports are opened to container B, and the IP address of A is also exported by the name of container A. Eg in mybash run</p><pre># All env vars from &#39;db&#39; will be prefixed with &#39;db&#39;<br>&gt; env</pre><pre># Ping container A<br>&gt; ping db</pre><p>Using this option, we can easily connect to the MySQL db from within our container. We will need to make some changes in Startup.cs though to make a MySQL connection. Right now we have specified the connection string Server element as localhost; to connect from within our container, it needs to be the MySQL container’s name i.e. db because the MySQL server’s IP is exported with the name of the MySQL container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3055e19894fe0ceb63f8c02b858ab5a9/href">https://medium.com/media/3055e19894fe0ceb63f8c02b858ab5a9/href</a></iframe><p>Finally, let’s run the service:</p><pre># Build the image<br>&gt; docker-compose -f .\Docker\docker-compose.yml build --no-cache<br>&gt; docker-compose -f .\Docker\docker-compose.yml up builder</pre><pre># Note we can&#39;t yet start our service using docker-compose since it doesn&#39;t link to the MySQL container yet.<br># The compose up operation would have created a volume called docker_appbuild.<br>&gt; docker run --name webapp.test -p 5000:7909 -v docker_appbuild:/app --link db -dit webapp:0.1.0</pre><p>You can test the service using Postman, or the cURL commands mentioned in the 1st article. Eg:</p><pre># Add a new department<br>&gt; curl -X POST \<br>  <a href="http://localhost:5000/api/Department/">http://localhost:5000/api/Department/</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: ce786dd0-5d17-bc94-81d3-8191203649cb&#39; \<br>  -d &#39;{<br> &quot;Name&quot;: &quot;CSE&quot;<br>}&#39;</pre><pre># Get a department by id<br>&gt; curl -X GET \<br>  <a href="http://localhost:5000/api/Department/1">http://localhost:5000/api/Department/1</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: 9402340e-d28b-8ae7-4265-8d2ce3ca33aa&#39;</pre><h3>Running with docker-compose</h3><p>So far we have manually created the MySQL and service containers. We had to run multiple commands to create, link, and run each container. As if that wan’t bad enough, if we change the credentials, table name, or container name of the MySQL server we will need to change the connection string in the web app container too.</p><p>Docker-compose can help us reduce the number of steps needed to spawn the containers. Using environment variables in the docker-compose.yml file we can create a single point of control for the db credentials, and the connection string.</p><p>Modify the existing compose file to add a new MySQL service, and link it to webapp.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0a975b444f9cde4494ac3b7dcb692e7/href">https://medium.com/media/d0a975b444f9cde4494ac3b7dcb692e7/href</a></iframe><p>The MySQL service is pretty straight forward. We use the mysql-server image from docker hub, and map a persistent storage. What is new is the environment and env_file sections. These sections allow us to define environment variables inside our container — akin to using docker run with the -e option.</p><ul><li>The environment tag takes a dictionary with each entry describing the &lt;key&gt;:&lt;value&gt;. Here we pass MYSQL_RANDOM_ROOT_PASSWORD as !!str yes. &quot;yes&quot; could also have been used, but simple yes would not work as that would be a Boolean value.</li><li>The env_file tag takes a list of file paths (relative to the compose file). These files are similar to the .env file introduced in the previous section. They contain a list of &lt;key&gt;=&lt;value&gt; pairs.</li></ul><p>secrets.env will contain our db credentials, and table name.</p><pre># Ideally, this should not be in the source control<br>MYSQL_DATABASE=Students<br>MYSQL_USER=user_name_1<br>MYSQL_PASSWORD=my-secret-pw</pre><h4>A note on environment variables again</h4><p>Unlike the .env file, the environment and env_file tags do not substitute variables in the compose file. They are used solely to populate environment variables <strong><em>inside</em></strong> the container. So they can’t be used to subsitute values in the build, image, and container_name tags.</p><p>That is why the variable MYSQL_SERVER_NAME is not defined in secrets.env, we need to add an entry for it in .env.</p><pre># MySQL vars in .env<br>MYSQL_SERVER_NAME=db</pre><h4>Linking to web app</h4><p>The webapp section of the compose file has also been modified to include secrets.env and pass in MYSQL_SERVER_NAME to denote the MySQL container name.</p><p>The link between webapp and mysql is described using the link tag. A link is an automatic dependency, and hence we don’t need to add mysql to the depends_on tag.</p><p>Note: The link and depends_on tag will just ensure that the dependency container is started before the webapp container. They do not ensure that the service inside the container has started i.e. in this case just because the db container started, doesn’t mean that MySQL server has finished initializing. It is our responsibility to wait for the db to be ready before connecting to it.</p><h4>Running the service</h4><p>Because we are storing all our db configurations — including container name, credentials, table name, etc — in sercrets.env and .env and passing them as environment variables to the containers, we don’t need to hard code the connection string in the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2723c89431470bb3e62d2b2abe00448c/href">https://medium.com/media/2723c89431470bb3e62d2b2abe00448c/href</a></iframe><p>We create the connection string by accessing the values of the environment variables we passed into our container.</p><p>In order to ensure that the MySQL container is ready before we connect permanently, we use exponential back-off in the WaitForDBInit function.</p><p>We can finally run our service using</p><pre># Clean up<br>&gt; docker stop webapp.test; docker stop db; docker container prune; docker volume prune;</pre><pre># Build new images<br>&gt; docker-compose -f .\Docker\docker-compose.yml build --no-cache<br>&gt; docker-compose -f .\Docker\docker-compose.yml up -d</pre><p>The MySQL container takes approximately a minute to finish initializing. The service will be ready when it is able to connect to the db. We can check the stdout of webapp using docker logs webapp.test.</p><h3>Conclusion</h3><p>We have successfully connected to a MySQL container from another container. But there is little point of using containers if we can’t use it in distributed settings. In the future, I hope to explore how to run and manage db clusters easily using container orchestration tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3827e006e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET core and MySQL with Docker — Part 2]]></title>
            <link>https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-2-ee7fba1fc508?source=rss-390a13b6896a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee7fba1fc508</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Likhit Dharmapuri]]></dc:creator>
            <pubDate>Sat, 07 Oct 2017 21:24:03 GMT</pubDate>
            <atom:updated>2017-10-07T21:38:22.420Z</atom:updated>
            <content:encoded><![CDATA[<h4>Move your build to a build container to decouple your build system.</h4><p>This article is the second part of a series of 3 posts:</p><ol><li><a href="https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-1-b7ef538ecd8e">Creating and containerizing the web API using a in memory db</a></li><li>Building the code inside a container and using docker compose (this)</li><li><a href="https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-3-e3827e006e3">Connecting the web service to a MySQL container</a></li></ol><p>The full code can be found <a href="https://github.com/Likhit/Docker-With-ASP-Core-and-MySQL">here</a>.</p><p>In the previous post we created a simple ASP.NET core web API using an in memory database and successfully ran it as a container. The container used DLLs built on the host machine. In this post we’ll look at a way to containerize the build system itself without building your code in the production container. We will also see how we can spawn our app using docker-compose.</p><h3>Building ASP.NET core apps in Docker</h3><p>The architecture for our new build system looks a bit like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*MTcCHyW3cIR_4fc7MjJsvA.png" /></figure><p>We have two images represented by two docker files</p><ol><li>Build.dockerfile will spawn a container to build our source code. It will copy the source code into the container, and build it with dotnet publish. The build output will be copied into a docker managed volume (more on that below).</li><li>App.dockerfile is our modified production image definition. I will link to the docker managed volume and run the app using dotnet &lt;dll&gt;.</li></ol><p>Because docker containers run in isolation, we need a way to share the build output between the two containers. We use a <a href="https://docs.docker.com/engine/admin/volumes/volumes/">docker volume</a> to do that; it is akin to attaching a shared folder to each container. First the builder container will build the solution and publish to the volume. Then the volume is attached to the production container which will run the dlls in the volume.</p><p>The dockerfile definitions are (placed in a folder named Docker):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32520e37b282579af2f19821993b5f1f/href">https://medium.com/media/32520e37b282579af2f19821993b5f1f/href</a></iframe><p>The App.dockerfile definition is almost unchanged. The only difference is that we are no longer coping the publish folder from our host to the container. Instead, as we’ll see, the container will expect the dlls to be present in the working directory.</p><p>Build.dockerfile uses the official ASP.NET core development container. This container includes the dotnet SDK, which we need to build our code. The dockerfile takes two arguments namely BUILD_CONFIG and BUILD_LOCATION both of which are consumed by our RUN command. BUILD_CONFIG can take two values Debug, or Release. BUILD_LOCATION tells dotnet publish which folder to put the built dlls in.</p><p>We do not need to attach any volume to build images from the dockerfiles; but we will need one when creating containers from the images. To build the images run:</p><pre># Build builder image<br>&gt; docker build -f .\Docker\Build.dockerfile -t webapp:Build --build-arg BUILD_CONFIG=Debug .</pre><pre># Build prod image<br>&gt; docker build -f .\Docker\App.dockerfile -t webapp:0.1 --build-arg URL_PORT=7909 .</pre><p>Now create the volume necessary to spawn the containers. Run docker volume create appbuild to create a volume named appbuild. You can see all volumes you have created using docker volume ls.</p><p>Since Build.dockerfile uses the RUN command, the dotnet publish operation executes during the image build. This means that the required dlls have already been created at /app/out in the image. To access these files and have them copied to our volume, we will just create a container (not run) with our appbuild volume mapped to /app/out.</p><pre># Create a container to copy dlls to appbuild<br>&gt; docker create --name webapp.builder -v appbuild:/app/out webapp:Build</pre><pre># Test that the dlls have been copied to appbuild by creating a simple bash container with the volume attached<br>&gt; docker run --name bash -v appbuild:/app --workdir /app bash ls</pre><pre># The response should be<br>ContainerProd.PrecompiledViews.dll<br>ContainerProd.PrecompiledViews.pdb<br>ContainerProd.deps.json<br>ContainerProd.dll<br>ContainerProd.pdb<br>ContainerProd.runtimeconfig.json<br>publish<br>web.config</pre><p>Great! We now have our build stored in the volume appbuild. We can now run our application by mapping appbuild to the /app folder inside a container spawned from webapp:0.1.</p><pre># Run the application<br>&gt; docker run --name webapp.test -v appbuild:/app -p 5000:7909 -d webapp:0.1</pre><pre># Check the logs to see if app is running<br>&gt; docker logs webapp.test</pre><p>Awesome, now we have a containerized build system. We can test the container from our host with the same cURL commands mentioned in the previous post. Eg:</p><pre># Add a new department<br>&gt; curl -X POST \<br>  <a href="http://localhost:5000/api/Department/">http://localhost:5000/api/Department/</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: ce786dd0-5d17-bc94-81d3-8191203649cb&#39; \<br>  -d &#39;{<br> &quot;Name&quot;: &quot;CSE&quot;<br>}&#39;</pre><pre># Get a department by id<br>&gt; curl -X GET \<br>  <a href="http://localhost:5000/api/Department/1">http://localhost:5000/api/Department/1</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: 9402340e-d28b-8ae7-4265-8d2ce3ca33aa&#39;</pre><p>But running it is kind of clumsy; we need to execute a bunch of commands to build and run the app, and the volume.</p><h3>Running the app with docker-compose</h3><p><a href="https://docs.docker.com/compose/">Docker-compose</a> is a tool we can use to define and run multi-container services. The tool takes in a YAML file describing each container and dependency chain.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15180ba1fc96bdea46b86121f9705bc4/href">https://medium.com/media/15180ba1fc96bdea46b86121f9705bc4/href</a></iframe><p>In the Docker folder create a docker-compose.yml file. A quick glance should be enough to understand how the file is representing our docker build and docker run commands. Let’s go through some of the components:</p><ul><li>version specifies the compose format version that docker-compose should use to interpret the file.</li><li>A compose file defines services, networks, and volumes at the top level. services define our containers and their inter-dependencies. volumes declare the name and properties of the volumes we want to create (using docker volume).</li><li>You can see that we created a volume name appbuild in the volume section. We could define other properties (like volume size) etc. but right now the defaults will suffice.</li><li>The build tag describes how to build the container images. Remember, the format for docker build goes like docker build -f &lt;dockerfile&gt; --build-arg &lt;ARG_NAME&gt;=&lt;VALUE&gt; -t &lt;TAG_NAME&gt; &lt;CONTEXT&gt;. The context usually the current folder i.e .; but in the case of the compose file, since it is in the Docker folder, the context is set to ../. The docker file is the path of the docker file to build from the context. args specifies a list of arguments to pass to the image build. Here we are using environment variables to read the value of our build args.</li><li>The image tag specifies the image to use for the service. If the image isn’t present locally it will try to download it from hub.docker.com. Since, we have a build tag, docker-compose up will build an image of the &lt;TAG_NAME&gt; the first time it is run. Every subsequent run will use the created image. To recreate the image from scratch use docker-compose build --no-cache.</li><li>The container_name tag specifies the name of the created container.</li><li>The volumes tag inside a service specifies the &lt;volume_name&gt;:&lt;container_path&gt;; similar to specifying the -v &lt;volume_name&gt;:&lt;container_path&gt; flag in docker run.</li><li>The ports tag similarly defines the -p &lt;host_port&gt;:&lt;container_port&gt; flag. Note that we have used string instead of ints to represent the ports. This is because YAML interpreters can sometimes parse the format xx:yy in base 60 instead of base 10.</li><li>Finally, to show that webapp should only be run after we run builder we use the depends_on tag in webapp. This can take an array of other services that the current service depends on.</li></ul><h4>Running the service</h4><p>To start the web service run:</p><pre># First define the environment vars (assuming powershell):<br># Webapp vars<br>&gt; $env:WEBAPP_VERSION=0.1.0<br>&gt; $env:URL_PORT=7909</pre><pre># Builder vars<br>&gt; $env:BUILDER_VERSION=0.1.0<br>&gt; $env:BUILD_CONFIG=Debug<br>&gt; $env:BUILD_LOCATION=/app/out</pre><pre># Start webapp<br>&gt; docker-compose -f ./Docker/docker-compose.yml up webapp</pre><pre># Start webapp in detached mode<br>&gt; docker-compose -f ./Docker/docker-compose.yml up -d webapp</pre><p>To stop the web service (if started in detached mode)”</p><pre># Stop the service<br>&gt; docker-compose stop</pre><pre># Stop service and remove generated containers<br>&gt; docker-compose rm -s</pre><h4>A note on environment variables</h4><p>While starting the service, if the environment variables are not specified docker will assume blank strings. We can set defaults for the variables by creating a .env file in the folder from which we run docker-compose up. docker-compose will automatically search for this file. You can see what your compose file looks like after environment variable substitution using docker config.</p><p>The format of the .env file:</p><pre># This is a comment.<br># The vars are defined using &lt;key&gt;=&lt;value&gt;<br># Ensure there is no space between the &#39;=&#39; and &lt;key&gt;, &lt;value&gt;</pre><pre># Webapp vars<br>WEBAPP_VERSION=0.1.0<br>URL_PORT=7909</pre><pre># Builder vars<br>BUILDER_VERSION=0.1.0<br>BUILD_CONFIG=Debug<br>BUILD_LOCATION=/app/out</pre><p>To override the defaults specified in the .env file we can set the variables again in the shell when running docker-compose. For example to run a release build:</p><pre>&gt; $env:BUILD_CONFIG=&quot;Release&quot;<br>&gt; docker-compose -f ./Docker/docker-compose.yml up -d</pre><p>Notice how this creates a new builder image named webapp:0.1.0.Release and a new web service image named webapp:0.1.0.Debug. This is because docker-compose couldn’t find any image satisfying the image: webapp:${BUILDER_VERSION}:${BUILD_CONFIG} name constraints; so it built new images with those names.</p><h3>Next steps</h3><p>We have successfully built the solution inside an image and are able to spawn new builds and run them with a single command using docker compose. This makes our run and build configs available for source control.</p><p>But our web service is still using an in-memory database. In the next post we will create a MySQL container, and link the web service container to use it. We will need to use our docker volume knowledge to persist the MySQL container data, and docker compose to express the db-webapp dependency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7fba1fc508" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASP.NET core and MySQL with Docker — Part 1]]></title>
            <link>https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-1-b7ef538ecd8e?source=rss-390a13b6896a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ef538ecd8e</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[entity-framework]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Likhit Dharmapuri]]></dc:creator>
            <pubDate>Sat, 07 Oct 2017 21:17:12 GMT</pubDate>
            <atom:updated>2017-10-07T21:36:02.571Z</atom:updated>
            <content:encoded><![CDATA[<h4>Connect an ASP.NET core container to a MySQL container using docker-compose.</h4><p>I have been meaning to ramp up on Docker and integrate it into my workflow for a while now. Enough <a href="https://www.youtube.com/watch?v=Xig72IxkEms">dilly-dallying</a>. To get started I created a toy ASP.NET core 2.0 Web API container connected to a MySQL container. While putting up a hack was straightforward, it took a lot more effort to spin up the two containers programmatically and elegantly with a single build file.</p><p>I initially meant to write a single post, but it quickly exploded into a 3000 words essay. So I divided it into a series of 3 posts covering:</p><ol><li>Creating and containerizing the web API using a in memory db (this)</li><li><a href="https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-2-ee7fba1fc508">Building the code inside a container and using docker compose</a></li><li><a href="https://medium.com/@Likhitd/asp-net-core-and-mysql-with-docker-part-3-e3827e006e3">Connecting the web service to a MySQL container</a></li></ol><p>The full code can be found <a href="https://github.com/Likhit/Docker-With-ASP-Core-and-MySQL">here</a>.</p><h3>Creating the Web API</h3><p>We’ll start with first creating a web service using an in memory database. This will help us containerize the app without worrying about communication with an external db.</p><p>Let’s start with first creating an empty project by running dotnet new empty.</p><p>The application is a toy student database. We will have just 2 tables in our database: Student, and Department. Create a Models folder to for our Plain Old C# Objects (POCO) to represent the database tables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/406d81e1e3ddf7d7c7b902379b1f4f7f/href">https://medium.com/media/406d81e1e3ddf7d7c7b902379b1f4f7f/href</a></iframe><p>Next create the DbContext:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b59e733c7dec21fa55517b512ddb6bad/href">https://medium.com/media/b59e733c7dec21fa55517b512ddb6bad/href</a></iframe><p>We will inject the DbContext into our controllers using dependency injection instead of creating a new object inside each controller. To do this modify Startup.cs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd03bc9415f078094687b33af738765/href">https://medium.com/media/cfd03bc9415f078094687b33af738765/href</a></iframe><p>Now we define the controllers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18bdce9b0f578093a4b1fef75ee6f449/href">https://medium.com/media/18bdce9b0f578093a4b1fef75ee6f449/href</a></iframe><p>At this point we have a working application. Run it with dotnet run. By default the API will run at <a href="http://localhost:500.">http://localhost:5000</a>. We will change the port when we run the API within docker. You can test the API with cURL:</p><pre># Add a new department<br>&gt; curl -X POST \<br>  <a href="http://localhost:5000/api/Department/">http://localhost:5000/api/Department/</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: ce786dd0-5d17-bc94-81d3-8191203649cb&#39; \<br>  -d &#39;{<br> &quot;Name&quot;: &quot;CSE&quot;<br>}&#39;</pre><pre># Get a department by id<br>&gt; curl -X GET \<br>  <a href="http://localhost:5000/api/Department/1">http://localhost:5000/api/Department/1</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: 9402340e-d28b-8ae7-4265-8d2ce3ca33aa&#39;</pre><pre># Add a student<br>&gt; curl -X POST \<br>  <a href="http://localhost:5000/api/Student/">http://localhost:5000/api/Student/</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: f63a259d-5c0a-baf5-3a56-583d672672a6&#39; \<br>  -d &#39;{<br> &quot;Name&quot;: &quot;John Doe&quot;,<br> &quot;DepartmentID&quot;: 1,<br> &quot;Email&quot;: &quot;<a href="/service/mailto:johndoe@doejohn.com">johndoe@doejohn.com</a>&quot;,<br> &quot;PhoneNumber&quot;: &quot;1122334455&quot;<br>}&#39;</pre><pre># Get a student by id<br>&gt; curl -X POST \<br>  <a href="http://localhost:5000/api/Student/">http://localhost:5000/api/Student/</a> \<br>  -H &#39;cache-control: no-cache&#39; \<br>  -H &#39;content-type: application/json&#39; \<br>  -H &#39;postman-token: f63a259d-5c0a-baf5-3a56-583d672672a6&#39; \<br>  -d &#39;{<br> &quot;Name&quot;: &quot;John Doe&quot;,<br> &quot;DepartmentID&quot;: 1,<br> &quot;Email&quot;: &quot;<a href="/service/mailto:johndoe@doejohn.com">johndoe@doejohn.com</a>&quot;,<br> &quot;PhoneNumber&quot;: &quot;1122334455&quot;<br>}&#39;</pre><h3>Containerizing the app</h3><p>Right now the app is running on your host, and not within a container. To containerize the app we need to define a Dockerfile. But before that let’s publish our app into a framework dependent package. Run dotnet publish -o .\publish. This should put a build with all dependencies included into the publish folder. We will use these to run the app inside a container.</p><p>To keep the root folder clean, create a new folder named Docker and create a file App.dockerfile</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfe22c476457204ec458cd509ba1396e/href">https://medium.com/media/dfe22c476457204ec458cd509ba1396e/href</a></iframe><p>Let’s deepdive over the various components in this file:</p><ul><li>FROM specifies the base image for the container. Here it is the official <a href="https://hub.docker.com/r/microsoft/aspnetcore/">ASP.NET core image</a> which is a linux container with ASP.NET core pre-installed. Note however that the dotnet SDK isn’t installed in this image; so you can’t build your sourse in this image.</li><li>ENV var_name default_value defines environment variables inside the container. The value can be overridden when the container is started.</li><li>LABEL allows the addition of metadata in the form of key=value to the image. You can use \ to split any Docker command into multiple lines.</li><li>ARG declares an argument that must be specified at build time. As mentioned before here we take the port number the web app should run on as an argument. Environment variables and arguments can be referenced using the ${var_name} syntax.</li><li>WORKDIR sets the current directory in the image. It is like running cd inside the image to the specified directory. All docker commands after WORKDIR is set use the specified directory as context.</li><li>ASPNETCORE_URLS is an environment variable used by ASP.NET core to set the IP:Port combination to listen to. This is set to <a href="http://*:${URL_PORT}.">http://*:${URL_PORT}</a>. Notice the *; it translates to 0.0.0.0. If you set the url to localhost, or 127.0.0.1 you will not be able to redirect requests from your host to your containers.</li><li>COPY is used to copy a directory from the host into the container. Here we are copying the contents of the publish folder into the app.</li><li>ENTRYPOINT specifies the command to run when the container starts. Here we start the web app by running dotnet &lt;project_name&gt;.dll</li></ul><p>You can find a more detailed explanation for each command <a href="https://docs.docker.com/engine/reference/builder/">here</a>. We can now build an image from the dockerfile:</p><pre># Build image (from root folder). Run the app at port 7909.<br>&gt; docker build -f .\Docker\App.dockerfile -t webapp:Debug --build-arg URL_PORT=7909 .</pre><p>This creates an image named webapp:Debug; use docker images to list images available locally. Now let’s finally create a container from this image:</p><pre># Run the container. Expose the container&#39;s <br>&gt; docker run --name webapp.test -p 5000:7909 -it webapp:Debug</pre><p>Once the container starts, you should see a running container named webapp.test when you run docker ps -a. You can test the endpoint using the same cURL commands used above. Docker will redirect all traffic to localhost:5000 to webapp.test at port 7909.</p><h3>Next Steps</h3><p>Right now we are building the solution on the host machine and running the app in a container. Wouldn’t it be better to build the code in a container too? That way our build system is independent of our host, and can be guaranteed to run on any machine (in a container).</p><p>One way to do that would be to copy the code into the container and build and run it in the same container using dotnet run; but we wouldn’t normally want production containers to have the source code in them.</p><p>The next post will explore how we can create a dedicated build container, and then use its output in our production container.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ef538ecd8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>