<?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 Patrick Hanbury on Medium]]></title>
        <description><![CDATA[Stories by Patrick Hanbury on Medium]]></description>
        <link>https://medium.com/@patrickhanbury1?source=rss-b8cbdb1e946c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gPy_dLMoec6BVqQ8SzddTg.jpeg</url>
            <title>Stories by Patrick Hanbury on Medium</title>
            <link>https://medium.com/@patrickhanbury1?source=rss-b8cbdb1e946c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:37:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patrickhanbury1/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[Monte Carlo Simulations with Python (Part 1)]]></title>
            <link>https://medium.com/data-science/monte-carlo-simulations-with-python-part-1-f5627b7d60b0?source=rss-b8cbdb1e946c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5627b7d60b0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[monte-carlo]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Patrick Hanbury]]></dc:creator>
            <pubDate>Fri, 25 Jan 2019 18:46:55 GMT</pubDate>
            <atom:updated>2019-01-26T17:38:09.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19y3uResL7apNrLApZMc3A.jpeg" /><figcaption>Monte Carlo’s can be used to simulate games at a casino (Pic courtesy of Pawel Biernacki)</figcaption></figure><p>This is the first of a <em>three part series</em> on learning to do Monte Carlo simulations with Python. This first tutorial will teach you how to do a basic “crude” Monte Carlo, and it will teach you how to use importance sampling to increase precision. Part 2 will introduce the infamous metropolis algorithm, and Part 3 will be a specialized piece for budding physicists (we’ll learn how to use Monte Carlo simulations to solve problems in quantum mechanics!)</p><p>Monte Carlo methods are widely used heuristic techniques which can solve a variety of common problems including optimization and numerical integration problems. These algorithms work by cleverly sampling from a distribution to simulate the workings of a system. Applications range from solving problems in theoretical physics to predicting trends in financial investments.</p><h3>The Task</h3><p>In this introduction, we will develop a Python implementation of Monte Carlo approximations to find a solution to this integral:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*_lBuwnD8apXirH-IQV7sNw.png" /><figcaption>Integral we will approximate using Monte Carlo methods</figcaption></figure><p>I’m borrowing this example and it’s solution from Sunkanta Deb’s <a href="https://www.ias.ac.in/article/fulltext/reso/019/08/0713-0739"><em>Variational Monte Carlo Technique</em></a> article. If you’re looking to learn more about simulating quantum mechanical systems using Monte Carlos, definitely check out that article.</p><p>You’ll notice that this integral cannot be solved analytically, and therefore we will need to approximate it numerically. Let’s start with a simple approach to the problem: the Crude Monte Carlo.</p><h3>The Crude Monte Carlo: Intuition</h3><p>The Crude Monte Carlo is the easiest technique to understand, so we’ll start here. But as the name suggests, it’s also the least accurate. We’ll fix this later though. :)</p><p>You may recall from high school calculus the following identity, which shows how to calculate the average value of a function (for a proof, check out this <a href="http://tutorial.math.lamar.edu/Classes/CalcI/ProofIntProp.aspx#Extras_IntPf_AvgVal">link</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*eQfCG8SwYsJA4pZzoFg8Og.png" /><figcaption>This theorem is used to find the average value of a function</figcaption></figure><p>Just as we can find the average value of a function by integrating, we can also find the value of an integral by determining the average value of it’s integrand, <em>f(x)</em>. The Monte Carlo technique is built upon this principle: instead of evaluating an indefinite integral, which can sometimes be impossible, let’s instead estimate the average of the integrand and use that to approximate the integral.</p><p>And that’s exactly what we’re going to do! So how do we do that?</p><p>Well, the easiest way to do it would be to randomly sample input values <em>x</em> from all possible input values. Let’s say we have a simple linear function, like <em>y = 2x</em>, and we want to find the average value of <em>y</em> in the range [0,2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*AcBgIq8Nl-vHW7VslRgSrw.png" /><figcaption>Approximating the average of y = 2x using 10 randomly selected values</figcaption></figure><p>To calculate the average, we’ll just evaluate <em>y</em> at all randomly determined <em>x</em> and average the results.</p><p>This process is exactly the Crude Monte Carlo. Now let’s see how use this technique in Python to solve our problem from earlier.</p><h3>The Crude Monte Carlo: Implementation</h3><p>You can find all of the code for this tutorial on my Github <a href="https://github.com/pat-hanbury/MonteCarloTutorial/blob/master/MonteCarloExample.ipynb">here</a>. Here’s the start of our code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/877bd801d916d229130edaecc5558fcf/href">https://medium.com/media/877bd801d916d229130edaecc5558fcf/href</a></iframe><p>We really don’t need much. numpy will be used once to find the minimum argument of a list. We&#39;ll use math for defining our functions and random will be used for sampling. matplotlib will help visualize our results as we go.</p><h3>Some Helpful Functions</h3><p>First let’s define a function to generate a random number in a particular range.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f87f62ea5f2c20e836c923fe1da2b799/href">https://medium.com/media/f87f62ea5f2c20e836c923fe1da2b799/href</a></iframe><p>Let’s also define our integrand function, <em>f(x)</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bff8f7b9ec31accf127dbb5470a3035c/href">https://medium.com/media/bff8f7b9ec31accf127dbb5470a3035c/href</a></iframe><h3>Perform the Crude Monte Carlo</h3><p>Implementing the Crude Monte Carlo should be fairly straightforward. Our algorithm looks like this:</p><ol><li>Get a random input value from the integration range</li><li>Evaluate the integrand</li><li>Repeat Steps 1 and 2 for as long as you like</li><li>Determine the average of all these samples and multiple by the range</li></ol><p>Let’s see what it looks like in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1b9e3077e9b57a350b4f758dc8d46b5/href">https://medium.com/media/e1b9e3077e9b57a350b4f758dc8d46b5/href</a></iframe><p>Performing this approximation with N=10000 samples gave me an estimate of 0.6994. Not too far off from <a href="https://www.wolframalpha.com/input/?i=integral+of+0+to+inf+of+e%5E(-x)%2F(1%2B(x-1)%5E2)">Wolfram&#39;s approximation</a> of 0.696092 (which we&#39;ll take to be the Holy Truth).</p><h3>Determine the Variance of Our Estimation</h3><p>But how confident are we in our answer? How do I know that 10,000 samples is enough to get a good approximation. We can quantify our accuracy by finding the <em>variance</em> of our estimations. The variance is defined to be <em>“the average of the square distances from the mean” . </em>It can be be shown to equal this equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*sTK3ikVARtF3MXHJK9rFxQ.png" /><figcaption>General Variance Equation</figcaption></figure><p>The variance gives us an idea of how much <em>f(x)</em> varies in the domain of <em>x.</em> It should be constant with the number of samples used, but we can calculate the error in integration by taking the square root of the variance divided by the number of samples. For more information on variance, check out Professor Adrian Feiguin’s <a href="https://github.com/afeiguin/comp-phys/blob/master/10_01_montecarlo_integration.ipynb">Monte Carlo Integration</a> notebook, or <a href="http://mathworld.wolfram.com/Variance.html">Wolfram’s article</a> on variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jyrsW7f3KTrs9C5diAnwQ.png" /><figcaption>Equation for calculating the variance in our Crude Monte Carlo simulation</figcaption></figure><p>This is the equation for variance we’ll use in our simulations. Let’s see how to do this in Python.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaf766bfd2c985109b81a80b2e8867c6/href">https://medium.com/media/eaf766bfd2c985109b81a80b2e8867c6/href</a></iframe><p>This implementation of the Crude Monte Carlo gave me a variance of 0.266 which corresponds to an error of 0.005. For a quick, back of the envelop estimate, this isn&#39;t bad at all, but what if we need a lot more precision? We could always just increase the number of samples, but then our computation time will increase as well. What if, instead of using random sampling, we cleverly sampled from the right distribution of points... we might call this, <em>importance sampling</em>.</p><h3>Importance Sampling: The Intuition</h3><p>Importance sampling is a method for reducing the variance of a Monte Carlo simulation without increasing the number of samples. The idea is that instead of randomly sampling from the whole function, let’s just sample from a distribution of points similarly shaped to the function.</p><p>Let’s say you have a step function that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*C4xsqQMS2lSgJAmvY7wSSA.png" /><figcaption>Graph of a step function and it’s “weight function” g(x)</figcaption></figure><p>Shown above we have a step function active on the range [0,2] and inactive from [2,6]. Sampling 10 times might yield estimates like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*r6mDsLGxtIwBJIbiAS0vIw.png" /><figcaption>10 sample estimation of f(x)</figcaption></figure><p>These samples (which I swear are random) correspond to a most likely distribution of samples, and yield an integral estimation of 1.8. But, what if instead, we estimate the <em>ratio</em> between our function <em>f(x)</em> and some special weight function <em>g(x)</em> whose value is almost always about 1/2 the value of <em>f(x)</em> for any given x? What if we also bias our samples to appear in the most active ranges of our function (which we’ll find to minimize the error). You’ll see that that the average of these ratios is a lot closer the real value of our integral, which is <em>2</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*DiDRtEcGK_K0R9BqrRiKbw.png" /><figcaption>Estimation of step function area using importance sampling</figcaption></figure><p>The importance sampling method is used to determine this optimal function <em>g(x)</em>.</p><h3>The Math</h3><p>I will provide a quick overview of importance sampling mathematics, but the main purpose of this post is the implementation, so if you desire more mathematical rigor, check out Deb’s <a href="https://www.ias.ac.in/article/fulltext/reso/019/08/0713-0739">article</a> I mentioned earlier.</p><p>Let’s see if we can find a <em>g(x)</em> such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*bP7vxbgH9ypsrxXvPlzIbw.png" /><figcaption>For some constant k</figcaption></figure><p>Basically, we want g(x) to look like a scaled version of f(x).</p><p>We’ll also need <em>g(x)</em> to satisfy a few criteria:</p><ol><li><em>g(x)</em> is integrable</li><li><em>g(x)</em> is non-negative on [a,b]</li><li>The indefinte integral of <em>g(x)</em>, which we’ll call <em>G(x), </em>has a real inverse</li><li>The integral of <em>g(x)</em> in the range [a,b] must equal 1</li></ol><p>In ideal case, <em>f(x)</em> = <em>k * g(x)</em>, where k is a constant. However, if <em>f(x)</em> = <em>k * g(x)</em>, then <em>f(x)</em> would be integrable and we would have no need to perform a Monte Carlo simulation; we could just solve the problem analytically!</p><p>So, we’ll settle for <em>f(x)</em> <strong>≈</strong> <em>k * g(x)</em>. We won’t get a perfect estimate of course, but you’ll find it performs better than our crude estimation from earlier.</p><p>We’ll define <em>G(x)</em> as follows, and we’ll also perform a change of variables to <em>r</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*vBdcmUv5CdUPIe8Ln4AWrg.png" /><figcaption>Definition of G(x)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*T2B0vmL-Of26Zky7WqlIaQ.png" /><figcaption>Change of variables to r (where r will be random samples between 0 and 1)</figcaption></figure><p><em>r</em> will be restricted to the range [0,1]. Since the integral of <em>g(x)</em> was defined to be 1, <em>G(x)</em> can never be greater than 1, and therefore <em>r</em> can never be greater than one. This is important because later, we will randomly sample from <em>r</em> in the range [0,1] when performing the simulation.</p><p>Using these definitions, we can produce the following estimation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*HiyhLZJE-8vubd7m3uvETw.png" /></figure><p>This sum is what we will be calculating when we perform the Monte Carlo. We’ll randomly sample from <em>r</em> in order to produce our estimate.</p><p>Simple right? Don’t be intimated if this doesn’t make sense at first glance. I intentionally focused on the intuition and breezed through the math quite a bit. If you’re confused, or you just want more mathematical rigor, check out the <a href="https://www.ias.ac.in/article/fulltext/reso/019/08/0713-0739">resource</a> I talked about earlier until you believe that final equation.</p><h3>Importance Sampling: Python Implementation</h3><p>Ok, now that we understand the math behind importance sampling, let’s go back to our problem from before. Remember, we’re trying to estimate the following integral as precisely as we can:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*_lBuwnD8apXirH-IQV7sNw.png" /><figcaption>Integral we’re trying to approximate</figcaption></figure><h3>Visualizing our Problem</h3><p>Let’s start by generating a template for our <em>g(x) </em>weight function. I’d like to visualize my function <em>f(x)</em>, so we’ll do that using matplotlib:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65d4063bf477f58dd8b3cef1d2aed263/href">https://medium.com/media/65d4063bf477f58dd8b3cef1d2aed263/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*cttm1PkgebLoqxRJIEsC4Q.png" /><figcaption>Plotting this function will help us determine an optimal structure of g(x)</figcaption></figure><p>Ok, so we can see that our function is <em>mostly</em> active in the rough range of [0,3-<em>ish</em>] and is <em>mostly</em> inactive on the range [3-<em>ish</em>, inf]. So, let’s see if we can find a function template that can be parameterized to replicate this quality. Deb’s proposes this function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*ux4Qa_FHIB6uYMgQonPefA.png" /><figcaption>Proposed weight function template [1]</figcaption></figure><p>After we find the ideal values for <em>A</em> and <em>λ,</em> we’ll be able to construct this plot of <em>f(x)</em> and our optimal weight function <em>g(x)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*yBLx55RYABdKAcpfrIw1Lw.png" /></figure><p>You can see that in many ways <em>g(x)</em> does not ideally replicate the shape of <em>f(x)</em>. This is ok. A crude <em>g(x)</em> can still do marvels for decreasing your estimation’s variance. Feel free to experiment with other weight functions <em>g(x)</em> to see if you can find even better solutions.</p><h3>Parametrize g(x)</h3><p>Before we can perform the simulation, we will need to find the optimal parameters <em>λ </em>and <em>A</em>. We can find <em>A(</em> <em>λ)</em> using the normalization restriction on <em>g(x)</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*pzlr95evBogKVE7p_EJV9A.png" /><figcaption>The normalization condition on g(x) can be used to prove that A(<em>λ)</em> = <em>λ</em></figcaption></figure><p>Now, all we need to do is find the ideal <em>λ</em>, and we’ll have our ideal <em>g(x)</em>.</p><p>To do this, let’s calculate the variance for different <em>λ </em>on the range [0.05,3.0] in increments of 0.5, and use the <em>λ </em>with the lowest variance<em>. </em>When using importance sampling, we calculate the variance of the ratio between f (x) and g(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFavyqMif8naN31iVgll3w.png" /><figcaption>General equation for variance when using importance sampling</figcaption></figure><p>And we’ll want to use this equation to approximate the integral:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*HiyhLZJE-8vubd7m3uvETw.png" /></figure><p>We’ll recalculate the variance for different <em>λ</em>, changing the weight function accordingly each time. After, we’ll use our optimal <em>λ </em>to calculate the integral with minimal variance.</p><p>The algorithm will look like this:</p><ol><li>Start at <em>λ = 0.05</em></li><li>Calculate the variance</li><li>Increment <em>λ</em></li><li>Repeat steps <em>2 </em>and <em>3</em> until you reach the last <em>λ</em></li><li>Pick the <em>λ </em>with the lowest variance — this is your optimal <em>λ</em></li><li>Use importance sampling Monte Carlo with this <em>λ </em>to calculate the integral</li></ol><p>In code, finding the optimal <em>λ</em> looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d93d7483fbbd7d425a9aef2383c86a10/href">https://medium.com/media/d93d7483fbbd7d425a9aef2383c86a10/href</a></iframe><p>You’ll see that running this optimization code using 10,000 samples produces a <em>λ</em> value of 1.65 , and a variance of 0.0465, which corresponds to an error of 0.022. Wow! Using importance sampling allowed us to reduce our error by a factor of 2 with the same number of samples.</p><h3>Run the Simulation</h3><p>Now, all we have to do is run the simulation with our optimized <em>g(x)</em> function, and we’re good to go. Here’s what it looks like in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6267242a66bddbb24e4b8d607f86acc2/href">https://medium.com/media/6267242a66bddbb24e4b8d607f86acc2/href</a></iframe><p>Running this code gave me an approximation of 0.6983 which is much closer to the Wolfram-provided grand truth of 0.696.</p><h3>Wrapping Things Up</h3><p>In this tutorial, we learned how to perform Monte Carlo simulations for estimating a definite integral. We used both the crude method and the importance sampling method, and found that importance sampling provided a significant decrease in the error.</p><p>Check back soon for Part 2 of this tutorial where we’ll go over how to use the metropolis algorithm in your Monte Carlo simulations!</p><p>Good luck, and as always feel free to drop questions and comments :)</p><h3>References and Further Reading</h3><p>[1] <a href="https://www.ias.ac.in/article/fulltext/reso/019/08/0713-0739">Variational Monte Carlo Technique by Sukanta Deb</a></p><p>[2] <a href="https://github.com/afeiguin/comp-phys/blob/master/10_01_montecarlo_integration.ipynb">Computation Physics Examples by Adrian Feiguin</a></p><p>[3] <a href="http://mathworld.wolfram.com/Variance.html">Variance by Eric Weisstein (Wolfram)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5627b7d60b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/monte-carlo-simulations-with-python-part-1-f5627b7d60b0">Monte Carlo Simulations with Python (Part 1)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Launch Docker Containers with the Official Python Library]]></title>
            <link>https://medium.com/@patrickhanbury1/how-to-launch-docker-containers-with-the-official-python-library-31dbe1bff8ca?source=rss-b8cbdb1e946c------2</link>
            <guid isPermaLink="false">https://medium.com/p/31dbe1bff8ca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Patrick Hanbury]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 20:03:29 GMT</pubDate>
            <atom:updated>2019-01-10T20:03:29.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*gDW_hAhf5n7WfLZfD4Ky2Q.jpeg" /></figure><h3>Motivation</h3><p>Docker is a fantastic containerization tool. It helps users launch apps and run programs in various development and production environments almost effortlessly, but few Docker users seem to know about the fantastic <a href="https://docker-py.readthedocs.io/en/stable/">Python-SDK for Docker</a>. Built by Docker, this library lets you launch and maintain containers using Python code. I put together this tutorial for semi-experienced Docker users to quickly familiarize themselves with the power of a Pythonic approach to launching and managing Docker objects.</p><h3>Pre-Reqs</h3><p>Understand Docker (at least a little bit). I won’t be reviewing the key Docker concepts, so if you’ve never used Docker before, check out these great links first:</p><ol><li><a href="https://docs.docker.com/engine/docker-overview/">Official Docker Docs and Overview</a></li><li><a href="https://docs.docker.com/compose/overview/">Official Docker Compose Docs and Overview</a></li><li><a href="https://medium.com/@chathuranga94/introduction-to-docker-5c4a151c02e2">Introduction to Docker</a></li><li><a href="https://hackernoon.com/practical-introduction-to-docker-compose-d34e79c4c2b6">A Practical Introduction to Docker Compose</a></li></ol><h3>Tutorial: Let’s get Started</h3><p>You can find all the code for this tutorial on my Github <a href="https://github.com/pat-hanbury/Python-Docker-Tutorial">here</a>.</p><p>For this tutorial, we will use Docker to launch a simple <em>Django To Do</em> app, courtesy of <a href="https://github.com/rHuggler/django-todo">rHuggler </a>. We’ll launch a front-end container web, a back-end container api, and a database container db. We&#39;ll then link these containers with a custom bridge network djang-net. You don&#39;t need to understand Django to do this tutorial, but just that we have multiple active containers that need to communicate.</p><h3>Installation</h3><p>Assuming you have Docker and Python installed on your machine, all you need is a quick pip install from the command line:</p><pre>pip install docker</pre><h3>Get the Repo</h3><p>Let’s start with setting up our project. I’ll be using Linux for this tutorial, but you should manage fine from any computer if you’ve already set up Docker. From the command line, create and enter your home directory.</p><pre>mkdir tutorial <br>cd tutorial</pre><p>Now lets clone our Django app using git.</p><pre>git clone https://github.com/rHuggler/django-todo</pre><p>In the root directory of the repo, you’ll find a docker-compose.yml file. Because docker is so self-contained, most of the information we need to successfully launch the application will be found in the docker-compose.yml file, reprinted below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a941759976a1554b5a7083af95d012dc/href">https://medium.com/media/a941759976a1554b5a7083af95d012dc/href</a></iframe><p>This docker-compose.yml file gives us all the information we need regarding ports, volumes, environmental variables ect, so we&#39;ll just take that information directly from here.</p><p>A quick inspection of the <a href="https://github.com/rHuggler/django-todo/blob/master/README.md">README</a> file suggests we’ll need to run multiple commands in our web and api containers in order to set up Django correctly. To make it easier, you should put these commands in tutorial/django-todo/api/django_todo/back.sh and tutorial/django-todo/web/vue-todo/front.sh. Later, when we launch our containers, all we need to do is run these shell scripts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de7d7b63fca612d380378b6496f3831/href">https://medium.com/media/8de7d7b63fca612d380378b6496f3831/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/412238a1e8c4f9dfe8d30f509d0fe120/href">https://medium.com/media/412238a1e8c4f9dfe8d30f509d0fe120/href</a></iframe><h3>Setup the Docker Client</h3><p>Now let’s get to the Python. In the home directory tutorial, create dockerize.py and add these lines.</p><pre>from docker import from_env <br>import os <br>client = from_env()</pre><p>The from_env function returns a client object configured from environmental variables. This allows you to connect to the Docker daemon from Python.</p><h3>Build Your Images</h3><p>Next, we’ll want to build our images. To do this we’ll need to specify the directory containing our Dockerfile for both the front-end container web and the back-end container api.</p><pre># get paths<br>repo_dir = os.path.join(&#39;/absolute/path/to/tutorial&#39;, &#39;django-todo&#39;)<br>web_pth = os.path.join(repo_dir, &#39;web&#39;)<br>api_pth = os.path.join(repo_dir, &#39;api&#39;)</pre><pre># build images<br>web_img, logs = client.images.build(path=web_pth, tag=&#39;web&#39;)<br>api_img, logs = client.images.build(path=api_pth, tag=&#39;api&#39;)</pre><h3>Build a Bridge Network</h3><p>Now, for our application, we could use the default bridge network, but why don’t we create our own custom network to see how that works. We’ll do it by using the create function as follows.</p><pre>net_name = &#39;djang-net&#39;<br>net = client.networks.create(name=net_name, driver=&#39;bridge&#39;)</pre><p>The client.networks.create function creates and launches the network, so to connect to it, we only need to reference it by it&#39;s net_name.</p><h3>Run Containers</h3><p>Let me first introduce the code for launching our containers, and then I’ll explain how to customize the containers for the Django app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cd196dc180c3cf048dba779e2885d16/href">https://medium.com/media/9cd196dc180c3cf048dba779e2885d16/href</a></iframe><p>client.containers.run is the key method used to create and launch our containers. We will customize our containers by passing in different parameters. The one required parameter is the image, which can either be the Docker image name as a string (&#39;postgres:10&#39;) or an image object (web_img).</p><h4>ports</h4><p>Ports can be exposed, using a dictionary, in which the key is formatted as &#39;port/protocol&#39; and the value is an integer corresponding to host port you want to open. To open ports on a container, pass this dictionary into the ports argument of the client.containers.run command.</p><pre>#example<br>api_ports  =  {&#39;8000/tcp&#39;  :  8000}</pre><h4>detach</h4><p>Set this parameter to True in order to return a Container object. This is useful if you want to manipulate your containers after running them.</p><h4>name</h4><p>This is the name of the container, which is important because it is how the containers will know how to communicate with each other. For example, if the web container needs to send information to the back-end container api, it will send this information to api:8000.</p><h4>network</h4><p>Connect your container to a network by passing the network name as a string.</p><h4>volumes</h4><p>Mounting volumes is essential for most applications of Docker. To do this, we pass in a dictionary of a dictionary, in which the key is the source volume, and the value is a dictionary containing bind and mode information, formatted as follows:</p><pre># general format<br>{&#39;path/to/src/vol1&#39;: {&#39;bind&#39;: &#39;/mnt/vol1&#39;, &#39;mode&#39;: &#39;rw&#39;},<br> &#39;path/to/src/vol2&#39;: {&#39;bind&#39;: &#39;/mnt/vol2&#39;, &#39;mode&#39;: &#39;ro&#39;}}</pre><pre># our application<br>api_vol =  { os.path.join(repo_dir,  &#39;api/django_todo&#39;) :  {<br>    &#39;bind&#39;:  &#39;/usr/src/app&#39;,  &#39;mode&#39;:  &#39;rw&#39;}  <br>    }</pre><p>The source path will be found on the host machine, and the bind path will be found within the container. The mode can either be read-write (&#39;rw&#39;) or read-only (&#39;ro&#39;).</p><h4>environment</h4><p>Environmental variables can be passed in as a list of strings, where each string is of the format &quot;VARIABLE_NAME=value&quot;.</p><pre>web_env  =  [&quot;HOST=0.0.0.0&quot;]</pre><h4>command</h4><p>Perhaps the most important parameter is the command, which will be executed when the container launches. You may recall that we wrote two shell scripts, back.sh and front.sh, each containing a series of commands that we want to execute. Using this shell-scripting method, all we have to do is call this shell script as a command and our containers will run all these commands.</p><h3>And…. that’s it!</h3><p>After all this, just run python dockerize.py and view your (hopefully) fully functional <em>To Do</em> web app at localhost:8080. You&#39;ll know everything is working if you can create a task, check it off, and delete it. If you have any questions, or comments, difficulties, or bugs, feel free to drop a comment and I&#39;ll try to help out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31dbe1bff8ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>