<?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 David Weber on Medium]]></title>
        <description><![CDATA[Stories by David Weber on Medium]]></description>
        <link>https://medium.com/@david.charles.weber?source=rss-1bb564a1e573------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZCdXeTY8HCdlN-Ye.</url>
            <title>Stories by David Weber on Medium</title>
            <link>https://medium.com/@david.charles.weber?source=rss-1bb564a1e573------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:21:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@david.charles.weber/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[Listen to Your Logs]]></title>
            <link>https://medium.com/@david.charles.weber/your-aws-app-is-trying-to-tell-you-a-secret-ed98781e56e2?source=rss-1bb564a1e573------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed98781e56e2</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[David Weber]]></dc:creator>
            <pubDate>Mon, 24 Sep 2018 16:33:40 GMT</pubDate>
            <atom:updated>2018-09-24T16:38:10.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1LI9TzwDU1l6IyJFBRcULw.jpeg" /><figcaption>Your logs have something to tell you</figcaption></figure><p>I recently deployed a Rails app to ECS on AWS. The application had spent the previous five years on Heroku. The transition would have changes, some things were worse and some things got way better. The change to our instrumentation was one of the things that became 100% better.</p><p>First off the new instrumentation couldn’t be a burden on the application. It is a Rails app, which are super solid but like all apps, we don’t want to burden it anymore than we have to. There are a hundred ways to instrument your application. We wanted to keep it simple. Monitor every action and log the amount of time spent in the view rendering and database runtime. This part is Rails specific, but you can do the same thing for any app. All that comes after is universal for AWS.</p><p><em>Note: AWS charges for everything. Using the below in your app will insure charges. We estimate about $25 for a production application with 100,000 active users a month.</em></p><p>For Rails, create an instrumentation.rb file in your config/initializers</p><p>Rails already instruments your application, that is where you logs come from. So we are just going to tap into that and have it do something else for us.</p><pre># First off subscribe to every notification that is coming from the action_controller<br>ActiveSupport::Notifications.subscribe &#39;process_action.action_controller&#39; do |_name, _start, _finish, _id, payload|<br>  # Build a hash that names the controller and uses the payload as the data. We will look at the format of this later</pre><pre>  hash = { name: &#39;action_controller&#39;, payload: payload }<br>  # Take your ruby hash and jsonify it. The following will print that as a string to your logger at the `warn` level</pre><pre>  Rails.logger.warn hash.to_json</pre><pre>end</pre><p>That initializer will produce something like the following for every single action your Rails app takes. It will look like this (But only at the Warn log level set in the initializer):</p><pre>{<br>     &quot;name&quot;: &quot;action_controller&quot;,<br>     &quot;payload&quot;: {<br>         &quot;controller&quot;: &quot;ApplicationController&quot;,<br>         &quot;action&quot;: &quot;healthcheck&quot;,<br>         &quot;params&quot;: {<br>             &quot;controller&quot;: &quot;application&quot;,<br>             &quot;action&quot;: &quot;healthcheck&quot;<br>         },<br>         &quot;format&quot;: &quot;html&quot;,<br>         &quot;method&quot;: &quot;GET&quot;,<br>         &quot;path&quot;: &quot;/healthcheck&quot;,<br>         &quot;status&quot;: 200,<br>         &quot;view_runtime&quot;: 0.4295310000088648,<br>         &quot;db_runtime&quot;: 0<br>     } <br>}</pre><p>If you aren’t using Rails, no problem you can still follow along, just make sure that your application is producing a string that looks like it should be json with the information you want to capture into a metric.</p><p>The next thing to ensure is that your application is sending its logs to CloudWatch Logs. That setup is beyond the scope of this article but you can read about doing it here:</p><ul><li><a href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html">Collect metrics and logs from Amazon EC2 instances and on-premises servers with the CloudWatch agent</a></li><li><a href="https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/send_logs_to_cwl.html">Sending Logs, Events, and Performance Counters to Amazon CloudWatch - Amazon Elastic Compute Cloud</a></li></ul><p>If you are using ECS like us this is super easy. On a container definition just ensure it looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*9mClKvB1oFLXBiHUZO83Yg.png" /><figcaption>Or `Auto-configure…`</figcaption></figure><p>Check your Cloudwatch Logs. Run your application and head over to Cloudwatch. Click Logs on the left. Then drill into your application until you see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aj2Nv1slvvZbrHq37N-m8w.png" /><figcaption>Hopefully you have more going on than just healthchecks though!</figcaption></figure><p>This is great, but wouldn’t it be even better to get some useful data, or even some graphs out of it? Wouldn’t it be nice if there was some way to convert these logs into a Cloudwatch Metric that is graph-able and can be called by your SDK?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Ug7xyIoatSb4bzCjqkoA6Q.png" /><figcaption>AWS Lambda for the rescue</figcaption></figure><p>From the AWS Console head over Lambda and create a new Lambda Function. Before writing your function you need to set it up. It should be triggered by CloudWatch Logs Select the log stream that matches where you logs are being placed. In our case that would be /ecs/my-application which was in the log configuration for ECS.</p><p>Don’t enable it just yet as you will want to make a few tests before letting it go into the wild to work. Next you will need to give your function an <em>Execution Role. </em>Which is not as ominous as it sounds. Make a new IAM role and give it a Cloudwatch access role to your liking. It must be able to at least write to Cloudwatch metrics.</p><p><strong>Important!</strong> You must also give the role a trust relationship. Otherwise you will find yourself wondering why logs are not making it to your metric. From the console, go to the IAM -&gt; Role and select Trust Relationship from the tab menu. Edit the relationship to add:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>      },<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;<br>    }<br>  ]<br>}</pre><p>Now for the Lambda Function itself. This is a Python3 Lambda that will be executed every-time a new log is written to Cloudwatch. The function is simple, it will take the event that is given it by Cloudwatch and execute the code. Below is commented to help put it together.</p><pre>import os<br>import json<br>import datetime<br>import dateutil<br>import boto3<br>import botocore<br>import base64<br>import gzip</pre><pre>cw = boto3.client(&#39;cloudwatch&#39;) # boto3 is the python sdk for AWS</pre><pre>def lambda_handler(event, context):<br>    cw_data = event[&#39;awslogs&#39;][&#39;data&#39;] # Get Data from the event<br>    compressed_payload = base64.b64decode(cw_data) # Data comes across as encoded, so decode it and make it into the payload variable<br>    uncompressed_payload = gzip.decompress(compressed_payload)<br>    payload = json.loads(uncompressed_payload)</pre><pre>cluster = os.environ[&#39;CLUSTER&#39;] # This is our ECS cluster, which is an env var of the lambda function<br>    <br>    log_events = payload[&#39;logEvents&#39;]<br>    <br>    for log_event in log_events:<br>        log = json.loads(log_event[&#39;message&#39;])<br>        payload = log[&#39;payload&#39;]<br>        print(payload)</pre><pre>print(&quot;Processing controller#action: {}#{}...&quot;.format(payload[&#39;controller&#39;], payload[&#39;action&#39;]))<br>        <br>        # Publish DB Runtime to Cloudwatch Metrics<br>        # The &#39;Namespace&#39; is where the metrics will appear in Cloudwatch Metrics</pre><pre>      resp = cw.put_metric_data(Namespace=&#39;RAILS&#39;,<br>                                  MetricData=[{<br>                                      &#39;MetricName&#39;: &#39;DBRuntime&#39;,<br>                                      &#39;Dimensions&#39;: [{<br>                                          &#39;Name&#39;: &#39;ClusterName&#39;,<br>                                          &#39;Value&#39;: cluster<br>                                      },<br>                                      {<br>                                          &#39;Name&#39;: &#39;Controller&#39;,<br>                                          &#39;Value&#39;: payload[&#39;controller&#39;]<br>                                      },<br>                                      {<br>                                          &#39;Name&#39;: &#39;Action&#39;,<br>                                          &#39;Value&#39;: payload[&#39;action&#39;]<br>                                      }],<br>                                      &#39;Timestamp&#39;: datetime.datetime.now(dateutil.tz.tzlocal()), #dateutil.tz.tzlocal()<br>                                      &#39;Value&#39;: payload[&#39;db_runtime&#39;],<br>                                      &#39;Unit&#39;: &#39;Milliseconds&#39;<br>                                  }])<br>                                  <br>        print(&quot;DBRuntime {} sent&quot;.format(payload[&#39;db_runtime&#39;]))<br>        </pre><pre># Add as many metrics in any format as you like to Cloudwatch Metrics. This will vary in your requirement. This example is only one of the metrics we are watching with this function.<br>    return {}</pre><p>The function utilizes the print command because it will also have its own Cloudwatch Logs prefix. Meaning you can check your Lambda by checking its logs in Cloudwatch!</p><p>The real fun part: once your Lambda is debugged and running it will be publishing a Cloudwatch metric datapoint for you every time a new log is ingested. After a few minutes have passed (it took about 15 for us) the custom Metrics started showing up in the console.</p><p>Here is a graph of the view render time and database runtime for specific actions over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDRYDC2X9u66ksCWjqzuGQ.png" /><figcaption>This data helps us quickly identify which actions are the most resource hungry</figcaption></figure><p>This is a huge mission accomplished for our needs. We now have a Cloudwatch metric that will track every time an action is performed by our application. It will keep a graph of time spent in the database layer, and time spent in the view rendering. The more items we add to the graph the more obvious our trouble places appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*xLxSxcW8q6IJjA3JRHVb-Q.png" /></figure><p>Most of the actions are running very quickly. The light blue line shooting to the top shows an action that can be fast, or can be slow. Other actions, which don’t appear to take place very often but still take longer than all others are floating dots. This gives us an instant bird’s eye view of what we will work on improving next. Without adding one dependency, gem or middleware to our application.</p><p>Here is a repo with a sample Lambda Function:</p><p><a href="https://github.com/davidcharlesweber/logs_to_cw_metric/blob/master/convert_lambda.py">davidcharlesweber/logs_to_cw_metric</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed98781e56e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some projects call for constant command line use.]]></title>
            <link>https://medium.com/@david.charles.weber/some-projects-call-for-constant-command-line-use-ded7a1ebbef3?source=rss-1bb564a1e573------2</link>
            <guid isPermaLink="false">https://medium.com/p/ded7a1ebbef3</guid>
            <category><![CDATA[news]]></category>
            <category><![CDATA[self-love]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[David Weber]]></dc:creator>
            <pubDate>Fri, 24 Aug 2018 20:48:05 GMT</pubDate>
            <atom:updated>2018-08-24T20:48:05.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Some projects call for constant command line use. Not to mention the time spent starting at a text editor. How about a 25 line Ruby script to break it up?</p><p>I keep a folder called bin that has a collection of command line tools that I use, a lot. One of tools I keep to break things up on long days is rest I just type rest into my terminal and I get the five current headlines with some formatting. I also get a really dumb dad joke in between each article. That touch helps with the current state of the news.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*d3eG9l1nYgJmohP2dHKIrg.png" /></figure><p>Creating and running the script is very easy. Make a rest.rb file and add the following:</p><pre>#!/usr/bin/env ruby</pre><pre>require &#39;httparty&#39;</pre><pre>require &#39;colorize&#39;</pre><p>The first line tells your terminal that this needs to be processed as Ruby. The httparty is to make the GET requests and colorize, well to color. (You may need to run gem install httparty and gem install colorize that’s a one time thing (per Ruby version))</p><p>Next we will get our news articles:</p><pre>response = HTTParty.get(</pre><pre>   &#39;https://newsapi.org/v2/top-headlines?country=us&amp;apiKey=${your api key here}&amp;pageSize=5&#39;</pre><pre>)</pre><p>Getting the api key is free and takes only a minutes from newsapi.org</p><p>The next bit will iterate over the returned object and issue a series of put commands for each article. Then just issue another HTTParty.get for your joke each time and you’re done!</p><pre>response[&#39;articles&#39;].each do |article|</pre><pre>  puts article[&#39;title&#39;].center(100).underline.bold</pre><pre>  puts article[&#39;description&#39;]</pre><pre>  puts article[&#39;url&#39;].light_white</pre><pre>  puts # line break or \n elsewhere if you want</pre><pre>  joke = HTTParty.get(</pre><pre>    &#39;https://icanhazdadjoke.com/&#39;,</pre><pre>    headers: {</pre><pre>      &#39;Accept&#39; =&gt; &#39;application/json&#39;</pre><pre>    }</pre><pre>  )</pre><pre>  puts joke[&#39;joke&#39;].center(100).blue</pre><pre>  puts # line break or \n elsewhere if you want</pre><pre>end</pre><p>Now to make it executable:</p><pre>chmod +x rest.rb</pre><p>You can rename the file to just rest by removing the .rb extension. And type rest into your terminal.</p><p>BONUS</p><p>If you want to run this from anywhere, put this file in a folder called bin in your HOME directory. Then add the bin directory to your path.</p><p>In .profile .bash_profile or .zshrc add export PATH=$PATH&quot;:$HOME/bin&quot; or export PATH=&quot;$HOME/bin:$PATH&quot; depending on your terminal setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aM4wPFhIBe6BZ4ANPHAeNg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ded7a1ebbef3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trying to Bury a Rails App]]></title>
            <link>https://medium.com/@david.charles.weber/trying-to-bury-a-rails-app-2b2b71ec5747?source=rss-1bb564a1e573------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2b71ec5747</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[David Weber]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 16:55:05 GMT</pubDate>
            <atom:updated>2018-08-03T16:55:05.695Z</atom:updated>
            <content:encoded><![CDATA[<p>There comes a time in an apps lifecycle that you have a responsibility to try to kill it. You need to know how your application will respond to loads of traffic. Will it scale at the right time and in the right way? Will it fall on its face? Hopefully everything will work out great. But maybe it won’t.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT39CQytimVHdjQlXO%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT39CQytimVHdjQlXO%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT39CQytimVHdjQlXO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="214" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b5daceabde7a0e413ca32e91b8f17c3/href">https://medium.com/media/9b5daceabde7a0e413ca32e91b8f17c3/href</a></iframe><p>This is where a litany of tools comes in handy. But before you pick a tool you need to know your target. In this case we will be attack a Rails application that is running in containers on AWS’s ECS service. Where your app is doesn’t matter. You just need a url. But this application has Devise authentication. So we have to deal with that. You can use Seige with some okay results. But we need to rigger download of assets. So that is where jMeter comes into play. You can read about jMeter here:</p><p><a href="https://jmeter.apache.org/">Apache JMeter™</a></p><p>But, you don’t really need to. Since we are in Rails, we will use Ruby to make a configuration file that jMeter will use to attack the application. For that we need a gem called ruby-jmeter You don’t need to read about that either, just follow along and you should be okay, maybe.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6UBpHgaXFDNAuttm%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6UBpHgaXFDNAuttm%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6UBpHgaXFDNAuttm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a8a5a871f88c46ce2ec342542c23548/href">https://medium.com/media/4a8a5a871f88c46ce2ec342542c23548/href</a></iframe><p>Open up your terminal, hopefully you have brew installed..</p><pre>brew install jmeter</pre><p>And then get the gem for Ruby…</p><pre>gem install ruby-jmeter</pre><p>Now lets create a rake file where we can build the jMeter configuration builder and run it</p><blockquote>rakefile.rb</blockquote><pre>desc &#39;Generate and execute jmeter test plan&#39;</pre><pre>task :execute_jmeter_plan do |t, args|</pre><pre> require &#39;ruby-jmeter&#39;</pre><pre> generate_report</pre><pre>end</pre><pre>def generate_report</pre><pre> uri = URI(&quot;https://your_awesome_rails_app.com&quot;)</pre><pre> domain = uri.host</pre><pre> test do</pre><pre>  threads count: 10, rampup: 10, duration: 120 do</pre><pre>   defaults domain: domain</pre><pre>   cookies policy: &#39;rfc2109&#39;, clear_each_iteration: true</pre><pre>   transaction &#39;Page Load Tests&#39; do</pre><pre>    user_defined_variables [{name: &#39;email&#39;, value: &#39;put_an_email@here.net&#39;}, {name: &#39;password&#39;, value: &#39;a_good_password_no_one_can_guess&#39;}]</pre><pre>    visit name: &#39;Visit Signin&#39;, url: &#39;/users/sign_in&#39; do</pre><pre>     extract name: &#39;csrf-token&#39;, xpath: &quot;//meta[@name=&#39;csrf-token&#39;]/@content&quot;, tolerant: true</pre><pre>      extract name: &#39;csrf-param&#39;, xpath: &quot;//meta[@name=&#39;csrf-param&#39;]/@content&quot;, tolerant: true</pre><pre>      extract name: &#39;authenticity_token&#39;, regex: &#39;name=&quot;authenticity_token&quot; value=&quot;(.+?)&quot;&#39;</pre><pre>    end</pre><pre>    http_header_manager name: &#39;X-CSRF-Token&#39;, value: &#39;${csrf-token}&#39;</pre><pre>    submit name: &#39;Submit signin&#39;, url: &#39;/users/sign_in&#39;,</pre><pre>     fill_in: {</pre><pre>       &#39;${csrf-param}&#39; =&gt; &#39;${csrf-token}&#39;,</pre><pre>       &#39;user[email]&#39; =&gt; &#39;${email}&#39;,</pre><pre>       &#39;user[password]&#39; =&gt; &#39;${password}&#39;,<br>&#39;authenticity_token&#39; =&gt; &#39;${authenticity_token}&#39;</pre><pre>      }</pre><pre>     visit name: &#39;Organizations&#39;, url: &#39;/organizations&#39;</pre><pre>     visit name: &#39;Posts&#39;, url: &#39;/posts&#39;</pre><pre>     visit name: &#39;Comment&#39;, url: &#39;/comment/1&#39;</pre><pre>     visit name: &#39;A HTML Asset&#39;, url: &#39;/htmls/21209&#39;</pre><pre>     visit name: &#39;A Post&#39;, url: &#39;/post/710&#39;</pre><pre>     visit name: &#39;My Profile&#39;, url: &#39;/profile&#39;</pre><pre>    end</pre><pre>    view_results_in_table</pre><pre>    view_results_tree</pre><pre>    graph_results</pre><pre>    aggregate_graph</pre><pre>   end</pre><pre> end.run(</pre><pre>   file: &#39;jmeter.jmx&#39;,</pre><pre>   log: &#39;jmeter.log&#39;,</pre><pre>   jtl: &#39;results.jtl&#39;</pre><pre>  )</pre><pre>end</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7btPCcdNniyf0ArS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7btPCcdNniyf0ArS%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMjA2M3h2a3V0cmRiZjV3bW10a3E0eWwzYTBiaTh2YmY1MnBtYTUyNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o7btPCcdNniyf0ArS%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/c024468167360d75ef959adcfaed632b/href">https://medium.com/media/c024468167360d75ef959adcfaed632b/href</a></iframe><p>Let’s break it down. This is a rake task than when executed will require the ruby-jemter gem then execute generate_report</p><p>generate_report will take the url we provide and prep it by pulling the domain, you can optionally get your port or other information if you need it here. The test will start with how you define your test specifics. Here we are running on 10 threads, the test will ramp up the number of requests over a duration of ten seconds and run the test for a total of 120 seconds.</p><p>defaults , cookiesand user_defined_variables will be used throughout the test. If you are hitting an application that is using SSL, which it better be, add protocal: “https&quot;, port: 443 to your defaults. The first two visits we make are the most complicated. First is to the signin page to get csrf-token and csrf-param which we extract. This is something that Devise uses to auth the sign in request so we need it. As well as the authorization_token .</p><p>That csrf-token and authorization_tokenare then submit ed with the email and password we defined earlier.</p><p>http_header_manager will do just what it’s name implies.</p><p>Now we can start visiting pages of our application with the visit command</p><pre>rake generate_jmeter_plan</pre><p>The last little bit will be our files locations. Be careful trusting the ruby-jmeter log when you have devise. Since devise will redirect to the login page you will get 200 codes even though you are not loading a page.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIs1O1TWV0LEJi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FIs1O1TWV0LEJi%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FIs1O1TWV0LEJi%2F200.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b567a447e4a3a13aae39330a28effb9/href">https://medium.com/media/0b567a447e4a3a13aae39330a28effb9/href</a></iframe><p>Now you can go really crazy and start raising the number of threads, the rampup time to be more realistic, and the duration to really simulate what your app will do.</p><pre>threads count: 100, rampup: 180, duration: 1200 do<br>...</pre><p>This test revealed that the scaling rules for this app are tremendously broken. This wouldn’t be obvious if we were just watching the cpu and memory use of the container instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMZcYhtQf-lYuBbMq17EXg.png" /><figcaption>Even with the alarm triggered the app could not scale quickly enough to meet the demand spike that happened in a three minute window.</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F11kEuHSQAXXiGQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F11kEuHSQAXXiGQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2282babe0a1b173f157dfe5a08bd7c8/href">https://medium.com/media/c2282babe0a1b173f157dfe5a08bd7c8/href</a></iframe><p>If we change the file extension of the results file to .csv we can open it in excel to make a pivot table to get a quick insight into problem pages we visited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*ovl4wo79rVDvkRCm_4QZEw.png" /></figure><p>There is an authorization error where a variable isn’t set without a proper host. So my app produced a crazy amount of 503 errors. Thousands of requests have been sent in this action. The average of elapsed is the response time average in milliseconds.</p><p>Now we know what to target for our app before launch, our scaling rules. The containers need to come up faster so we will reduce the grace period on launch. And fix the container instance issue with an instance per container, which is total overkill of our resources.</p><p>Off to work, happy load testing of your Rails app!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FVD9NtdBN9CwqQ%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FVD9NtdBN9CwqQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FVD9NtdBN9CwqQ%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="243" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6931c41fed1fa713c5064212e0b6bf3/href">https://medium.com/media/f6931c41fed1fa713c5064212e0b6bf3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2b71ec5747" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Github Repos and Elasticsearch with Rails]]></title>
            <link>https://medium.com/@david.charles.weber/github-repos-and-elasticsearch-with-rails-b572ba796409?source=rss-1bb564a1e573------2</link>
            <guid isPermaLink="false">https://medium.com/p/b572ba796409</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[David Weber]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 15:47:47 GMT</pubDate>
            <atom:updated>2018-07-03T15:48:01.562Z</atom:updated>
            <content:encoded><![CDATA[<p>By the end of the article we will have made a containerized Rails app, that will store github repos to a local database. Those records can then be searched locally with Elasticsearch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbBO1xNh3G5sYFlDnt64JQ.gif" /></figure><p>Start off by creating the rails app</p><pre>rails new github_searcher --database=postgresql<br>cd github_searcher</pre><p>Then create a controller to handle the home page, where our search box will be.</p><pre>rails g controller pages search</pre><p>Then in your routes file set your search page as the home page.</p><blockquote>config/routes.rb</blockquote><pre><em>Rails</em>.application.routes.draw do</pre><pre>  root &#39;pages#search&#39;</pre><pre>end</pre><h3>Containering</h3><p>That is enough to run the app and see the blank search page. But before we do we will setup the container and the local container cluster for all the magic.</p><p>You will need a Dockerfile in the root directory:</p><blockquote>Dockerfile</blockquote><pre>FROM ruby:2.5.0</pre><pre>RUN apt-get update -qq &amp;&amp; apt-get install -y build-essential libpq-dev nodejs</pre><pre>RUN mkdir /app</pre><pre>WORKDIR /app</pre><pre>COPY Gemfile Gemfile</pre><pre>COPY Gemfile.lock Gemfile.lock</pre><pre>RUN gem install bundler</pre><pre>RUN bundle install</pre><pre>COPY . .</pre><pre>EXPOSE 3000</pre><pre>CMD rails s -b 0.0.0.0 -p 3000</pre><p>This is a very basic Dockerfile that will start the application on port 3000.</p><p>We will also need a postgres database and an elastic search container all running at the same time. docker-compose will handle that for us. The following compose file, also in the root directory will start all three containers for us and make sure that they can communicate with each other.</p><blockquote>docker-compose.yml</blockquote><pre>version: &#39;3&#39;</pre><pre>services:</pre><pre>  app:</pre><pre>    build: .</pre><pre>    entrypoint: /app/docker_entry.sh</pre><pre>    command: rails s -b 0.0.0.0 -p 3000</pre><pre>    ports:</pre><pre>      - 3000:3000</pre><pre>    volumes:</pre><pre>      - .:/app</pre><pre>    environment:</pre><pre>      - ELASTICSEARCH_URL=elasticsearch</pre><pre>      - DEV_DATABASE_HOST=db</pre><pre>    depends_on:</pre><pre>      - db</pre><pre>      - elasticsearch</pre><pre>   # these allow you to debug with byebug by attaching to the container<br>    stdin_open: true</pre><pre>    tty: true</pre><pre>  elasticsearch:</pre><pre>    image: docker.elastic.co/elasticsearch/elasticsearch:6.3.0</pre><pre>    volumes:</pre><pre>      - .:/app</pre><pre>   environment:</pre><pre>     - cluster.name=docker-cluster</pre><pre>     - bootstrap.memory_lock=true</pre><pre>     - &quot;ES_JAVA_OPTS=-Xms512m -Xmx512m&quot;</pre><pre>   ports:</pre><pre>     - 9200:9200</pre><pre>   ulimits:</pre><pre>     memlock:</pre><pre>      soft: -1</pre><pre>      hard: -1</pre><pre>  db:</pre><pre>    image: postgres:latest</pre><pre>    ports:</pre><pre>      - 5432:5432</pre><pre>    environment:</pre><pre>      - POSTGRES_DB=github_searcher_development</pre><pre>      - POSTGRES_USER=root</pre><p>The extra confusing attributes in elasticsearch are required for elasticsearch to successfully start in that container. You will also need an entry point, in this case another file in the root directory called docker_entry.sh</p><blockquote>docker_entry.sh</blockquote><pre>#!/bin/bash<br>set -e</pre><pre>exec bundle exec &quot;$@&quot;</pre><p>Just need to let rails know where the database is by making this change to the database.yml</p><blockquote>database.yml</blockquote><pre>development:</pre><pre>  &lt;&lt;: *default</pre><pre>  database: github_searcher_development</pre><pre>  pool: 5</pre><pre>  timeout: 5000</pre><pre>  username: root</pre><pre>  host: db</pre><pre>  port: 5432</pre><p>Now to run it!</p><pre>docker-compose up --build -d</pre><p>A quick aside, you will need to run db:migratebut how do you attach to a container and issue a command? The -d in the previous command has your containers running in damean mode so all you need to do it tell which container what command to execute.</p><pre>docker-compose exec app rake db:migrate</pre><p>In your terminal if you attach you will see the logs from all three containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPsc3Z-nqGa6QmEzzp9YBA.png" /><figcaption>Note that if you `ctr+c` and then `docker-compose up` you will automatically be attached to all containers</figcaption></figure><p>Head over to localhost:3000 to see the app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otEOvNk6iRFZ032Vl_MiSw.png" /></figure><h3>Rails App</h3><p>In the search.html.erb file that the generate command created we will remove the generated stuff and add a form for the searching of github</p><blockquote>Delete this</blockquote><pre>&lt;h1&gt;Pages#search&lt;/h1&gt;</pre><pre>&lt;p&gt;Find me in app/views/pages/search.html.erb&lt;/p&gt;</pre><blockquote>Add this form which will remotely query github for us</blockquote><pre>&lt;%= form_tag(&#39;/search&#39;, remote: true) do %&gt;</pre><pre>  &lt;%= text_field_tag :search %&gt;</pre><pre>  &lt;%= submit_tag &quot;Submit&quot; %&gt;</pre><pre>&lt;% end %&gt;</pre><blockquote>routes.rb</blockquote><pre><em>Rails</em>.application.routes.draw do</pre><pre>  root &#39;pages#search&#39;</pre><pre>  post &#39;/search&#39;, to: &#39;pages#search_github&#39;</pre><pre>end</pre><blockquote>pages_controller.rb</blockquote><pre>class PagesController<em> &lt; ApplicationController</em></pre><pre>  def search</pre><pre>  end</pre><pre>  def search_github</pre><pre>    byebug</pre><pre>  end</pre><pre>end</pre><p>byebug is here so that you can see what is happening when you get to this point. Your home page will show like what is below, and if you submit a search byebug will stop your query. Make sure that you are in dameon mode -d from docker-compose. Then you can attach for debugging with docker attach github_searcher_app_1</p><p>This will allow you to query params in byebug and see what we are getting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_oQVyvsl2AR43AWDNoKJQ.png" /><figcaption>I very originally searched the term `i am searching this`</figcaption></figure><p>At this point I decided that being able to search by language might be useful so I added this to our form:</p><pre>&lt;%= select_tag &quot;language&quot;, options_for_select([ &quot;Ruby&quot;, &quot;Javascript&quot; ], &quot;Ruby&quot;) %&gt;</pre><p>Before we start capturing results to a local database we need a model to hold our data.</p><pre>rails g model repository repo_id:integer name:string owner:string owner_url:string html_url:string description:text stargazers_count:integer watcher_count:integer</pre><pre>docker-compose exec app rake db:migrate</pre><p>Now, all we need to do it issue a get request, capture the response from github, parse the json, loop through the results saving each one to the database.</p><pre>class PagesController<em> &lt; ApplicationController</em></pre><pre>  require &#39;net/http&#39;</pre><pre>...</pre><pre>  def search_github<br>    uri = URI(&quot;https://api.github.com/search/repositories?q=#{params[:search]}+language:#{params[:language]}&amp;sort=stars&amp;order=desc&quot;)</pre><pre>    res = <em>Net</em>::<em>HTTP</em>.get_response(uri)</pre><pre>    data = <em>JSON</em>.parse(res.body)</pre><pre>    data[&quot;items&quot;].each do |repo|</pre><pre>      record = <em>Repository</em>.find_by_repo_id(repo[&quot;id&quot;])</pre><pre>      unless record.present?</pre><pre>        record = <em>Repository</em>.new(repo_id: repo[&quot;id&quot;])</pre><pre>      end</pre><pre>      record.name = repo[&quot;name&quot;]</pre><pre>      record.owner = repo[&quot;owner&quot;][&quot;login&quot;]</pre><pre>      record.owner_url = repo[&quot;owner&quot;][&quot;html_url&quot;]</pre><pre>      record.html_url = repo[&quot;html_url&quot;]</pre><pre>      record.description = repo[&quot;description&quot;]</pre><pre>      record.stargazers_count = repo[&quot;stargazers_count&quot;]</pre><pre>      record.watcher_count = repo[&quot;watcher_count&quot;]</pre><pre>      record.save</pre><pre>    end</pre><pre>  end</pre><pre>end</pre><p>Notice that if a repo is searched multiple times it won’t appear in your database multiple times because the id is being used to identify it. This would also be a great use case for first_or_initialize</p><h3>Elastic Search</h3><p>For elasticsearch in rails we will use the searchkick gem.</p><pre># Gemfile<br>gem &#39;searchkick&#39;</pre><pre># teminal<br>bundle install</pre><pre># restart your server</pre><pre># repository.rb<br>class Repository<em> &lt; ApplicationRecord</em></pre><pre>  searchkick</pre><pre>end</pre><blockquote>pages_controller.rb</blockquote><pre>class PagesController<em> &lt; ApplicationController</em></pre><pre>  require &#39;net/http&#39;</pre><pre>  def search</pre><pre>    if params[:search]</pre><pre><em>      Repository</em>.reindex</pre><pre>      @repos = <em>Repository</em>.search(params[:search])</pre><pre>    end</pre><pre>  end</pre><pre>...</pre><pre>end</pre><p>Now all you need to do is pretty up the search inputs and the root page.</p><blockquote>application.html.erb</blockquote><pre>&lt;!DOCTYPE html&gt;</pre><pre>&lt;html&gt;</pre><pre>  &lt;head&gt;</pre><pre>    &lt;title&gt;GithubSearcher&lt;/title&gt;</pre><pre>    &lt;%= csrf_meta_tags %&gt;</pre><pre>    &lt;%= csp_meta_tag %&gt;</pre><pre>    &lt;%= stylesheet_link_tag    &#39;application&#39;, media: &#39;all&#39;, &#39;data-turbolinks-track&#39;: &#39;reload&#39; %&gt;</pre><pre>    &lt;%= javascript_include_tag &#39;application&#39;, &#39;data-turbolinks-track&#39;: &#39;reload&#39; %&gt;</pre><pre>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css&quot; integrity=&quot;sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm&quot; crossorigin=&quot;anonymous&quot;&gt;</pre><pre>  &lt;/head&gt;</pre><pre>  &lt;body&gt;</pre><pre>    &lt;%= yield %&gt;</pre><pre>    &lt;script src=&quot;https://code.jquery.com/jquery-3.2.1.slim.min.js&quot; integrity=&quot;sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;</pre><pre>    &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js&quot; integrity=&quot;sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;</pre><pre>    &lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js&quot; integrity=&quot;sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;</pre><pre>  &lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><blockquote>search.html.erb</blockquote><pre>&lt;div class=&quot;row&quot;&gt;</pre><pre>  &lt;div class=&quot;col-md-6&quot;&gt;</pre><pre>    &lt;h2&gt;Pull Github Repos&lt;/h2&gt;</pre><pre>    &lt;%= form_tag(&#39;/search&#39;, remote: true) do %&gt;</pre><pre>      &lt;div class=&quot;form-group&quot;&gt;</pre><pre>        &lt;label&gt;Search Term&lt;/label&gt;</pre><pre>        &lt;%= text_field_tag :search, nil, class: &quot;form-control&quot; %&gt;</pre><pre>      &lt;/div&gt;</pre><pre>      &lt;div class=&quot;form-group&quot;&gt;</pre><pre>        &lt;label&gt;Language&lt;/label&gt;</pre><pre>        &lt;%= select_tag &quot;language&quot;, options_for_select([ &quot;Ruby&quot;, &quot;Javascript&quot; ], &quot;Ruby&quot;), class: &quot;form-control&quot; %&gt;</pre><pre>      &lt;/div&gt;</pre><pre>      &lt;%= submit_tag &quot;Submit&quot;, class: &quot;btn btn-primary&quot; %&gt;</pre><pre>    &lt;% end %&gt;</pre><pre>  &lt;/div&gt;</pre><pre>  &lt;div class=&quot;col-md-6&quot;&gt;</pre><pre>    &lt;h2&gt;Search Local DB&lt;/h2&gt;</pre><pre>    &lt;%= form_tag(root_path, method: :get) do %&gt;</pre><pre>      &lt;div class=&quot;form-group&quot;&gt;</pre><pre>        &lt;label&gt;Search Term&lt;/label&gt;</pre><pre>        &lt;%= text_field_tag :search, nil, class: &quot;form-control&quot; %&gt;</pre><pre>      &lt;/div&gt;</pre><pre>     &lt;%= submit_tag &quot;Submit&quot;, class: &quot;btn btn-primary&quot; %&gt;</pre><pre>  &lt;/div&gt;</pre><pre> &lt;% end %&gt;</pre><pre> &lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;% if @repos.present? %&gt;</pre><pre>  &lt;div class=&quot;row&quot;&gt;</pre><pre>    &lt;% @repos.each do |r| %&gt;</pre><pre>      &lt;div class=&quot;col-sm-3&quot;&gt;</pre><pre>      &lt;div class=&quot;card&quot; style=&quot;width: 18rem;&quot;&gt;</pre><pre>        &lt;div class=&quot;card-body&quot;&gt;</pre><pre>         &lt;h5 class=&quot;card-title&quot;&gt;&lt;%= r.name %&gt;&lt;/h5&gt;</pre><pre>         &lt;h6 class=&quot;card-subtitle mb-2 text-muted&quot;&gt;&lt;%= r.owner %&gt;&lt;/h6&gt;</pre><pre>         &lt;p class=&quot;card-text&quot;&gt;&lt;%= r.description %&gt;&lt;/p&gt;</pre><pre>         &lt;%= link_to r.owner_url, class: &quot;card-link&quot; %&gt;</pre><pre>         &lt;%= link_to r.html_url, class: &quot;card-link&quot; %&gt;</pre><pre>      &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>   &lt;/div&gt;</pre><pre>  &lt;% end %&gt;</pre><pre> &lt;/div&gt;</pre><pre>&lt;% end %&gt;</pre><p>By first querying github, the local db is populated with github repos. Then I can query my local database to get what I am looking for!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygMYRFlyihiiSVticTvOHQ.gif" /></figure><p>Congrats! You can now start a rails app, containize it, run it along side a postgres container, and an elasticsearch container. You also know how to use all three at the same time, and as an added bonus you can hit an external API and do some basic formatting for your app not to mention debug your running container!</p><p>Here is the github repair if you just want to pull it.</p><p><a href="https://github.com/davidcharlesweber/github_searcher">davidcharlesweber/github_searcher</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b572ba796409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Docker Compose with Rails]]></title>
            <link>https://medium.com/@david.charles.weber/useful-docker-compose-with-rails-c6edcd0b9f13?source=rss-1bb564a1e573------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6edcd0b9f13</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[container-orchestration]]></category>
            <dc:creator><![CDATA[David Weber]]></dc:creator>
            <pubDate>Tue, 12 Jun 2018 20:21:00 GMT</pubDate>
            <atom:updated>2019-01-24T14:31:42.073Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s dive into the practical side of docker compose and what you can do when you run docker-compose with your rails application. I’ve assumed you have already made a DockerFile. If not a sample is included at the bottom of the article.</p><p>To be overly brief, docker-compose will cluster a series of containers together for you and take care of all the networking. It allows you to communicate among containers defined in your compose file by name. Here is the docker-compose file we will reference throughout:</p><pre>version: &#39;3&#39;</pre><pre>services:</pre><pre> app:</pre><pre>  build: .</pre><pre>  entrypoint: /bin/sh</pre><pre>  command: rails s -b 0.0.0.0 -p 3000</pre><pre>  ports:</pre><pre>   - 3000:3000</pre><pre>  volumes:</pre><pre>   - .:/app</pre><pre>  env_file: .env</pre><pre>  environment:</pre><pre>   - DEV_DATABASE_HOST=db</pre><pre>   - DEV_MAIL_HOST=mailcatcher</pre><pre>  depends_on:</pre><pre>   - db</pre><pre>  stdin_open: true</pre><pre>  tty: true</pre><pre> db:</pre><pre>  image: postgres:latest</pre><pre>  ports:</pre><pre>   - 5432:5432</pre><pre>  environment:</pre><pre>   - POSTGRES_DB=database-dev</pre><pre>   - POSTGRES_USER=root</pre><pre> delayed_job:</pre><pre>  build: .</pre><pre>  command: rake jobs:work</pre><pre>  volumes:</pre><pre>   - .:/app </pre><pre>  env_file: .env</pre><pre>  environment:</pre><pre>   - DEV_DATABASE_HOST=db</pre><pre>   - DEV_MAIL_HOST=mailcatcher</pre><pre> depends_on:</pre><pre>  - db</pre><pre>  stdin_open: true</pre><pre>  tty: true</pre><pre> mailcatcher:</pre><pre>  image: zolweb/docker-mailcatcher:latest</pre><pre>  ports:</pre><pre>   - &quot;1025:1025&quot; </pre><pre>   - &quot;1080:1080&quot;</pre><p>There is a lot going on here. We will actually be creating four containers, each with a unique purpose and allowing them all to communicate with each other in the cluster (the networking is handled by docker-compose).</p><p>First is the application itself, app. It is going to run the rails app on port 3000, and the port mapping of 3000:3000 is how you will be able to access it. If you run the application you can reach it at localhost:3000 because your 3000 is mapped to the container’s 3000.</p><p>The env variables will be loaded from .env and it will have a volume for it’s filesystem. DEV_DATABASE_HOST will be the db container and DEV_MAIL_HOST will be the mailcatcher container that comes up later in the docker-compose up command. The app depends on the db and won’t come up until the db is ready.</p><p>The delayed_job container is essentially the same thing, but it will run the worker instead of the application. You can tell this from the cmd or command line.</p><p>The database container is very easy to get up and going. You don’t need to have an image for it because it is part of the docker registry. Simply defining the image as postgres:latest means that the image will be downloaded for the container with the most recent version of postgres. If you want a versioned postgres use the version instead of latest. It will run your postgres on 5432, the default postgres port. Once it is up and running you can connect to it the same way that you would the app container.</p><p>Mailcatcher is much the same way. If you are not familiar with mailcatcher go read up on it. But it is a simple application for monitoring and intercepting outgoing mail from your application. It even has a simple web based client so you can see what your outbound emails look like. The compose file will download and build the container for you and the 1080 and 1025 ports are mapped for you in docker compose file. These are required by mailcatcher.</p><p>Now for the magic. docker-compose up --build -d This will look at your compose file and build the containers (you don’t need to build each time you run them). It will also run them in daemon mode so you can attach to them at later times of your choosing. You may have wondered about the stdin_open and tty lines in the compose file. They will allow you to attach to a container and debug (byebug). To get your list of container names: docker ps To attach, pick the name of a container and docker attach #{container name} You will see logs as they come through.</p><p>You can also perform tasks on a given container by using docker-compose and providing the container name as defined in the docker compose. docker-compose exec #{docker-compose container name} #{command you want to execute} Some popular ones would probably be:</p><p>docker-compose exec app rake db:migrate</p><p>docker-compose exec app rails c</p><p>You can pick any of your containers and run relevant commands in them such as psql using the exec which is short hand for execute.</p><p>To stop and start your containers:</p><p>docker start/stop #{container as found by docker ps}</p><p>Otherwise you can use docker-compose to control the whole cluster:</p><p>docker-compose up/down</p><p>Whenever you make certain changes, like gem files or ruby version it’s normally a good idea to docker-compose up --build to rebuild your containers.</p><p>As promised here is a sample DockerFile for a rails application:</p><pre># Pick the ruby version for your rails app. This one is a rails 4 app and using ruby 2.2.3. Consider using 2.5.0 at least.<br>FROM ruby:2.2.3</pre><pre># Installing some needed things here. Including ghostscript because this rails app works with pdfs. You may consider making adjustments. <br>RUN apt-get update -qq &amp;&amp; apt-get install -y build-essential libpq-dev nodejs &amp;&amp; apt-get install -y ghostscript<br></pre><pre># Make the directory for the app<br>RUN mkdir /app</pre><pre># Set the working directory of everything to the directory we just made.<br>WORKDIR /app</pre><pre># Copy the gemfile and gemfile.lock so we can run bundle on it<br>COPY Gemfile Gemfile</pre><pre>COPY Gemfile.lock Gemfile.lock</pre><pre># Install and run bundle to get the app ready<br>RUN gem install bundler</pre><pre>RUN bundle install</pre><pre># Copy the Rails application into place</pre><pre>COPY . .</pre><pre># Expose port 3000 on the container<br>EXPOSE 3000</pre><pre># Run the application on port 3000<br>CMD rails s -b 0.0.0.0 -p 3000</pre><p>Happy containering!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6edcd0b9f13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>