<?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 Matheus Villela Torres on Medium]]></title>
        <description><![CDATA[Stories by Matheus Villela Torres on Medium]]></description>
        <link>https://medium.com/@matheusvt?source=rss-12c072a8631f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x_gvrMHBwEO7jwFxKgo8bQ.jpeg</url>
            <title>Stories by Matheus Villela Torres on Medium</title>
            <link>https://medium.com/@matheusvt?source=rss-12c072a8631f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:51:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matheusvt/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[How to Build a Production-Ready ML Platform with Docker Compose]]></title>
            <link>https://matheusvt.medium.com/how-to-build-a-production-ready-ml-platform-with-docker-compose-064d2731fd1e?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/064d2731fd1e</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mle]]></category>
            <category><![CDATA[model-observability]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 19:41:56 GMT</pubDate>
            <atom:updated>2025-07-03T15:21:51.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the world of machine learning, building a model is only half the struggle. Taking that model to production — serving predictions reliably, monitoring performance, handling drift, and enabling continuous improvement — requires an entire ecosystem. This is where <strong>Machine Learning Engineering</strong> and <strong>MLOps</strong> come into play.</p><p>While Data Scientists focus on experimentation and accuracy, ML Engineers focus on <strong>productizing models</strong>: delivering scalable, observable, and maintainable systems. The intersection of this with DevOps practices has birthed <strong>MLOps</strong>, a discipline that incorporates CI/CD, reproducibility, monitoring, and automation into the machine learning lifecycle.</p><p>In this guide, I’ll show you how to build your own <strong>production-grade ML platform</strong> using <strong>Docker Compose</strong> and open-source tools like <strong>MLflow</strong>, <strong>Prometheus</strong>, <strong>Grafana</strong>, <strong>Kafka</strong>, and <strong>Elasticsearch</strong>. You’ll be able to train, serve, monitor, and compare machine learning models — all on your local machine using containers.</p><p>Although its “production-grade”, it’s highly recommend using scalable servers or services on cloud. This is just a practical demonstration.</p><blockquote><em>This post is based on this repository:<br> 👉 </em><a href="https://github.com/matheusvt2/model-serving-and-monitoring"><em>matheusvt2/model-serving-and-monitoring</em></a></blockquote><h3>Architecture Overview</h3><p>Our platform follows modern MLOps architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoAMhhtKZ47rJz8eTxtMUA.png" /><figcaption><strong>Figure 1.</strong> High level diagram.</figcaption></figure><p>We integrate:</p><ul><li><strong>Model Versioning and Tracking:</strong> MLflow + Postgres</li><li><strong>Artifact Storage:</strong> MinIO (S3-compatible)</li><li><strong>Model Serving:</strong> FastAPI (with Gunicorn + Uvicorn)</li><li><strong>Event Streaming:</strong> Kafka + Streaming Sink (Custom Python Code)</li><li><strong>Searchable Logs:</strong> Elasticsearch</li><li><strong>Metrics Collection:</strong> Prometheus</li><li><strong>Dashboards &amp; Alerts:</strong> Grafana</li></ul><h4>Services</h4><ul><li><strong>MLflow UI</strong>: <a href="http://localhost:5000/">http://localhost:5000</a></li><li><strong>Grafana</strong>: <a href="http://localhost:3000/">http://localhost:3000</a></li><li><strong>Prometheus</strong>: <a href="http://localhost:9090/">http://localhost:9090</a></li><li><strong>Elasticsearch</strong>: <a href="http://localhost:9200/">http://localhost:9200</a></li></ul><h3>Why Observability Matters</h3><p>Monitoring machine learning in production is <strong>not just about uptime</strong> — it’s about ensuring the model performs well <strong>over time</strong>.</p><p><strong>What do we observe?</strong></p><ul><li><strong>System Metrics</strong>: latency, CPU, memory, errors</li><li><strong>Model Metrics</strong>: prediction durations, output distributions</li><li><strong>Prediction Logs</strong>: full input/output audit trail</li><li><strong>Input data</strong>: distribution, correlation and importance</li></ul><blockquote><em>Together, these help you debug issues, detect data drift, analyze failures, and improve trust in your ML systems.</em></blockquote><h3>Hands-on</h3><p>Follow the steps below to spin up your ML platform locally.<br><strong>Minimum Requirements</strong>:</p><ul><li>Docker</li><li>Docker Compose</li><li>Linux/Unix system</li><li>16GB RAM, 4 CPU cores</li><li>Internet connection</li><li>10 GB free space</li></ul><h4>1. Clone the Repo</h4><pre>git clone https://github.com/matheusvt2/model-serving-and-monitoring.git<br>cd model-serving-and-monitoring</pre><h4>2. Start All Services</h4><pre>docker-compose up --build</pre><p>This launches:</p><ul><li>MLflow, MinIO, Postgres</li><li>FastAPI model server</li><li>Kafka, Streaming Sink</li><li>Prometheus, Grafana, Elasticsearch</li></ul><blockquote><em>Wait all services stabilize and create connections between each other.</em></blockquote><h4>3. Create MinIO bucket</h4><ul><li>Visit <a href="http://localhost:9001/">http://localhost:9001</a></li><li>Login with credentials from .env</li><li>Create a bucket named: mlflow</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qZUr9fL0r6M8dvFLyvHuQ.png" /><figcaption><strong>Figure 2.</strong> MinIO bucket.</figcaption></figure><h4>4. Train &amp; Register Your Model</h4><p>Open the notebook (modeling/classif.ipynb).</p><p>Run it in Jupyter or VS Code.<br> MLflow will automatically:</p><ul><li>Log the trained model</li><li>Save it in MinIO</li><li>Register it in the MLflow Registry</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8ATBsiJqs3tz35yXLE_9w.png" /><figcaption><strong>Figure 3. </strong>Model training and registration.</figcaption></figure><h4>5. Test the Prediction API</h4><p>The model serving API is already up via Docker.</p><p>First, create two alias in MlFlow UI, poduction and shadow (competitor), on registered models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6P_GbRZ9bR-fg4U_88cB_w.png" /><figcaption><strong>Figure 4. </strong>Model registered in MlFlow with aliases.</figcaption></figure><p>In serving/app.py, we use environment variables to dynamically load models from MLflow. This allows for flexible configuration across environments and simplifies model version management, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vkTLkKzEvB27MtutFHygCw.png" /><figcaption><strong>Figure<em> 5.</em></strong><em> Dynamic model loading from MLflow using environment variables within the application.</em></figcaption></figure><p>In this setup, we’re comparing two different models: the <strong>production model</strong>, a lightweight Random Forest Classifier optimized for speed and generalization; and a <strong>shadow model</strong>, a deliberately heavier and overfitted Random Forest Classifier. The second model was intentionally trained to be slower and less generalizable in order to highlight differences in performance and behavior across monitoring metrics, as shown in the snippet below.</p><pre># Create a heavier RandomForest classifier <br># Forcing an Overfit<br>robust_classifier = RandomForestClassifier(<br>    n_estimators=500,  <br>    max_depth=15,      <br>    min_samples_split=2,  <br>    min_samples_leaf=5,   <br>    max_features=&#39;sqrt&#39;,  <br>    bootstrap=True,     <br>    oob_score=True,       <br>    random_state=42,<br>    n_jobs=-1            <br>)</pre><p>To test the model responses, use the bash code inside <em>scripts</em> folder to send mutiple requests.</p><pre>bash scripts/calls.sh --N=100</pre><p>Each prediction is logged as an <strong>event to Kafka</strong> and <strong>metrics to Prometheus</strong>.</p><h4>6. Grafana Dashboard (Model Comparison)</h4><p>First, let’s configure the data sources for Grafana.</p><p><strong>Add Elasticsearch Data Source</strong></p><ol><li>Go to <strong>Connections</strong></li><li>Click <strong>Add new connection</strong> → <strong>Elasticsearch</strong></li><li><strong>URL:</strong> <a href="http://elasticsearch:9200/">http://elasticsearch:9200</a></li><li><strong>Authentication: No Authentication</strong></li><li><strong>Skip TSL certificate validation</strong></li><li><strong>Index name: </strong>predictions</li><li><strong>Time field name:</strong> `@timestamp`</li><li><strong>Save &amp; Test</strong></li></ol><p><strong>Add Prometheus Data Source</strong></p><ol><li>Go to <strong>Connections</strong></li><li>Click <strong>Add new connection</strong> → <strong>Prometheus</strong></li><li><strong>URL: </strong>http://prometheus:9090</li><li><strong>Authentication: No Authentication</strong></li><li><strong>Skip TSL certificate validation</strong></li><li><strong>Save &amp; Test</strong></li></ol><p>To import dashboard:</p><ol><li>Go to <strong>Grafana &gt; Dashboards &gt; Import</strong></li><li>Upload: monitoring/grafana/model_comparison_dashboard.json</li><li>Select data sources: Prometheus + Elasticsearch</li></ol><p>You’ll see:</p><ul><li>Prediction volumes and latency</li><li>Class distributions</li><li>Model agreement statistics</li><li>Shadow model performance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fCgPmAyiuqtcR68taqElhg.png" /><figcaption><strong>Figure 6. </strong>Dashboard in Grafana.</figcaption></figure><p>This dashboard provides a real-time comparison between a production and a shadow model, showing that both received the same number of prediction requests (1.10K), ensuring a fair evaluation. The shadow model exhibits significantly higher inference latency (~200ms vs. ~5ms) as expected from a deliberately heavier and overfitted version. While system resource usage remains low overall, class distribution differs between models, suggesting divergence in learned patterns. These visualizations highlight the importance of observability in identifying performance trade-offs and behavioral shifts before deploying new models to production.</p><h3>Advanced Usage</h3><p>You can extend this stack with:</p><ul><li>AB test deployments</li><li>Auto-retraining pipelines</li><li>CI/CD integrations with cloud services</li><li>Drift detection alerts</li><li>Accuracy monitoring over time</li></ul><p>This is a <strong>perfect playground</strong> for experimenting with real-world MLOps strategies.</p><h3>References &amp; Resources</h3><ul><li><a href="https://github.com/matheusvt2/model-serving-and-monitoring">GitHub Project</a></li><li><a href="https://blog.min.io/setting-up-a-development-machine-with-mlflow-and-minio/">MLflow + MinIO Guide</a></li><li><a href="https://prometheus.io/docs/introduction/overview/">Prometheus Docs</a></li><li><a href="https://grafana.com/docs/">Grafana Docs</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html">Elasticsearch Docker Guide</a></li></ul><h3>Final Thoughts</h3><p>This project is your <strong>launchpad into real MLOps</strong>. You now have:</p><ul><li>A versioning system</li><li>A model server</li><li>An event stream</li><li>Full observability</li><li>A dashboard for real-time insights</li></ul><p>Let’s keep pushing ML beyond the notebook!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=064d2731fd1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a static website using HUGO on Heroku]]></title>
            <link>https://matheusvt.medium.com/how-to-create-a-static-website-using-hugo-on-heroku-1217d7b66cd7?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1217d7b66cd7</guid>
            <category><![CDATA[site]]></category>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[godaddy]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 22:01:34 GMT</pubDate>
            <atom:updated>2022-06-06T22:50:14.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*m9FfgXpsD7bgya-MVgApuQ.png" /><figcaption>HUGO and Heroku logos.</figcaption></figure><h3>Intro</h3><p>I recently discovered HUGO (<a href="https://gohugo.io/">https://gohugo.io/</a>), a static website generator, written in Go and easy to use. The main advantage of using HUGO is the speed and practicality to create websites and personal blogs.</p><p>With the site generated, comes the question, where to host it? That’s where Heroku (<a href="https://www.heroku.com/">https://www.heroku.com/</a>) comes in, a cloud application hosting service. The most interesting thing about this platform is that it offers between 550–1,000 hours* of free hosting per month, meaning you won’t have to pay to host your website.</p><p>Heroku does not currently support using HUGO directly, so to get around this problem, we will create a Docker image with the necessary settings for it to be booted by Heroku.</p><h3>Prerequisites</h3><p>To perform this tutorial, you will need:</p><ul><li>Hugo — <a href="https://gohugo.io/getting-started/installing/">https://gohugo.io/getting-started/installing/</a></li><li>Heroku account — <a href="https://id.heroku.com/login">https://id.heroku.com/login</a></li><li>Heroku CLI — <a href="https://devcenter.heroku.com/articles/heroku-cli#install-the-heroku-cli">https://devcenter.heroku.com/articles/heroku-cli#install-the-heroku-cli</a></li><li>GitHub account** — <a href="https://github.com/">https://github.com/</a></li><li>Git CLI — <a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">https://git-scm.com/book/en/v2/Getting-Started-Installing-Git</a></li><li>Docker — <a href="https://docs.docker.com/engine/install/">https://docs.docker.com/engine/install/</a></li></ul><h3>Steps</h3><ol><li>Create a new website using HUGO</li><li>Link to GitHub**</li><li>Create app on Heroku</li><li>Download a Hugo theme and update config.toml</li><li>Create the Dockerfile and heroku.yml files</li><li>Test HUGO locally**</li><li><em>Commit</em> changes</li><li>Upload image to Heroku</li><li>Push changes</li><li>Website access</li></ol><p>BONUS — Custom domain with SSL</p><h3>Hands-On</h3><h4>1. Create a new website using HUGO</h4><p>First we will create a new site by the CLI (command-line interface).</p><p>Open your computer’s terminal (cmd on windows, terminal on linux and mac) and go to the folder where you would like to create your website.</p><p>In my case, I will create in the Documents folder.</p><p>Commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c087226815bf93a5efe1a8d9c1824f4/href">https://medium.com/media/0c087226815bf93a5efe1a8d9c1824f4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*yh6MBLPZC-sBvG9Aa8GqMA.png" /><figcaption>Command “hugo new site myhugosite” response.</figcaption></figure><h4>2. Link to GitHub**</h4><p>In the folder created by HUGO, initialize git and associate it with the repository on GitHub, which must be created before adding the remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*JI-JInQcOdFjU_v8ii7sgg.png" /><figcaption>Example of how to create repository on GitHub.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41762e4c1056668ba012c77e0de3466/href">https://medium.com/media/a41762e4c1056668ba012c77e0de3466/href</a></iframe><h4>3. Creat app on Heroku</h4><p>To create an app on Heroku, we can use both the graphical interface and the CLI, in this case, I’m using the CLI because it’s simpler. Having created the account on Heroku and installed the CLI, simply enter the commands below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebc12ed18a569ffdbbfb6f64ebd9df0e/href">https://medium.com/media/ebc12ed18a569ffdbbfb6f64ebd9df0e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*tBbWpeV6GkzDVEfGZsNUqw.png" /><figcaption>Command “heroku apps:create myhugosite” response.</figcaption></figure><p>Note that I’m logging in Heroku, creating an app called <em>myhugosite</em> and linking it to the repository that Heroku makes available to us.</p><h4>4. Download a Hugo theme and update config.toml</h4><p>In this step, your folder should have the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*2mrMLNLtw4DQjt8VpXY_Kw.png" /><figcaption>App structure created by Hugo.</figcaption></figure><p>If didn’t go through step 2, the difference is that you will not have the <em>README.md</em> and <em>.gitignore</em> files.</p><p>For this tutorial, let’s use <a href="https://github.com/StaticMania/hugo-cohub">hugo-cohub</a> theme, to search for other themes, just visit <a href="https://jamstackthemes.dev/#ssg=hugo">https://jamstackthemes.dev/#ssg=hugo</a> or <a href="https://themes.gohugo.io/">https://themes.gohugo.io</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bf08bfcbe096d65032995cad7a0cf49/href">https://medium.com/media/2bf08bfcbe096d65032995cad7a0cf49/href</a></iframe><p>By HUGO’s default, the themes must be cloned in the <strong>themes</strong> folder, so I’m passing the path<strong> themes/hugo-cohub</strong>. Note that I am removing .git from the cloned repository, I do this just so I don’t get references from other projects.</p><p>Now, let’s update <em>config.toml </em>file for our project. Note <em>baseURL</em> and <em>theme</em> fields. These are important for the correct use of the theme, the first one refers to the url generated by Heroku, the default is <strong>https://&lt;appname&gt;.herokuapp.com</strong>, in this case the url is <a href="https://myhugosite.herokuapp.com/">https://myhugosite.herokuapp.com</a>. The second refers to the name of the folder where the theme is located, in this case it is <em>hugo-cohub</em> (you don’t need to refer the <em>themes</em> path). The other settings are self-explanatory.</p><h4>5. Create Dockerfile and heroku.yml files</h4><p>We will now create a file called <em>Dockerfile</em> in the root of the app folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd06d4ed248fc225a50fdb3cc6efdf1/href">https://medium.com/media/9fd06d4ed248fc225a50fdb3cc6efdf1/href</a></iframe><p>Explaining: I’m using the <em>debian:stable-slim</em> image, copying all my files from the local folder <em>(.)</em> to the <em>/src </em>folder. After the copy, I install hugo clean the unnecessary files, create the hugo user, set the <em>/src</em> path as the default for the container and finally start hugo.</p><p>The next step is to create <em>heroku.yml</em>, this is the file that the platform will use to run the <em>build</em> and <em>run</em> steps. Documentation on how to write a <em>heroku.yml</em> is available at:</p><p><a href="https://devcenter.heroku.com/articles/build-docker-images-heroku-yml">https://devcenter.heroku.com/articles/build-docker-images-heroku-yml</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56fd55a3a52f73bd3e44251b1b3b03ee/href">https://medium.com/media/56fd55a3a52f73bd3e44251b1b3b03ee/href</a></iframe><p>Explaining: The first step to be performed is to build the image according to the <em>Dockerfile</em>, we name the generated image as <em>web</em>. In the next step, run, we run the command on the <em>web</em> image.</p><p>Arguments:<br>bind=0.0.0.0 → Bind the connection interface to the server (default “127.0.0.1”), if not set to “<strong>0.0.0.0</strong>” Heroku will not be able to access the server.</p><p>port=$PORT → Heroku assigns a random port to your Dyno, but makes that value available as an environment variable (default “1313”).</p><p>appendPort=false → If you don’t change it to <strong>false</strong>, all the links references will come with the port number, causing an error in directing and accessing links (default “true”).</p><p>baseURL=<a href="https://myhugosite.herokuapp.com/">https://myhugosite.herokuapp.com/</a> → hostname (and path) to the root, as we are using Heroku, we need to update according to the URL it offers us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuiX35PHr8jQRKa8AfVWfA.png" /><figcaption>File structure.</figcaption></figure><h4>6. Test HUGO locally**</h4><p>To test locally we will copy the contents of the <em>hugo-cohub/exampleSite</em> theme folders to the folders of the structure generated by Hugo. After copying, just start the server with <em>hugo server </em>command.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ed8597b759ff97b9ee6adb862ff9f5/href">https://medium.com/media/10ed8597b759ff97b9ee6adb862ff9f5/href</a></iframe><p>If all goes well, you will be able to access your site locally at <a href="http://localhost:1313/">http://localhost:1313/</a></p><h4>7. <em>Commit</em> changes</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6964a5851f4301b3db0495cbff840de/href">https://medium.com/media/f6964a5851f4301b3db0495cbff840de/href</a></iframe><h4>8. Upload image to Heroku</h4><p>According to <a href="https://devcenter.heroku.com/articles/container-registry-and-runtime#getting-started">heroku’s documentation</a>, to push the container Heroku’s registry, just hit the commands below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b47c7b953bd967a568fab83317d0449/href">https://medium.com/media/8b47c7b953bd967a568fab83317d0449/href</a></iframe><h4>9. Push changes</h4><p>To make changes to your site, simply save the changes locally, commit, and push to Heroku.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec41c35932026edf9e21282e6784bfe/href">https://medium.com/media/5ec41c35932026edf9e21282e6784bfe/href</a></iframe><p>If you performed step 2, we can configure Heroku to perform the deployments for each push you make to a <em>branch</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ls6t2o7S93S4leRpU6ORLw.png" /><figcaption>Deployment configuration via GitHub.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdpe1UFex5wSXTa9CWrxoQ.png" /><figcaption>Enabling automatic deployment from main branch.</figcaption></figure><h4>10. Website access</h4><p>To access the site, just wait for the build and deploy and access the link generated by Heroku (<strong>https://&lt;appname&gt;.herokuapp.com</strong>) or click on “Open app” button on your app’s <em>Overview</em> page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKZLrZiPFH1sKT0KyDCi-A.png" /><figcaption>Overview page.</figcaption></figure><h4>Example repository</h4><p><a href="https://github.com/matheusvt2/myhugosite">GitHub - matheusvt2/myhugosite</a></p><h3>BONUS — Custom domain with SSL</h3><h4>1. Domain purchase</h4><p>It is possible to use domains from several <em>registrars</em>, a famous example is GoDaddy, where it offers domains of various types.</p><h4>2. DNS Configuration</h4><p>First we will need to add a domain through the <em>Settings</em> tab of your app on Heroku, “Add domain” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxpoIcgjK7oWQAc81F5Mbg.png" /><figcaption>Domain configuration in the Settings tab.</figcaption></figure><p>Now just copy the generated “DNS Target” and change the CNAME value in your domain’s DNS settings (GoDaddy for example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zJLdU0SGFxPnVtu1BzpQg.png" /><figcaption>Configuração do DNS no registrador (GoGaddy).</figcaption></figure><p>IMPORTANT! → Still inDNS settings, configure permanent type (301) <em>Forwarding</em> for your domain address, for example: <a href="http://myhugosite.com/">http://myhugosite.com</a> or if you perform step 4, <a href="https://myhugosite.com/">https://myhugosite.com</a>.</p><h4>3. Update config.toml and heroku.yml</h4><p>In the <em>config.toml</em> and <em>heroku.yml</em> files change the <strong>baseURL</strong> value to your domain name, for example <strong>baseURL = ‘</strong><a href="http://myhugosite.com/&#39;"><strong>http://myhugosite.com/&#39;</strong></a> or <a href="https://myhugosite.com/"><strong>https://myhugosite.com/</strong></a> if you perform step 4.</p><h4>4. Upgrade Dyno to Hobby*** (7$ monthly).</h4><p>To upgrade you need to register your credit card in Account Settings → Billing. After setting up, just change the <em>Dyno</em> plan through the Resources tab of your app from <em>Free</em> to <em>Hobby</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*oHkzIqvPIB6LyZ_TrBBc7A.png" /><figcaption>Dyno types.</figcaption></figure><p>Then choose Automatic Certificate Management (ACM) form SSL Certificates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btIFhykNJ4p3r-36GttAmw.png" /><figcaption>SSL configuration.</figcaption></figure><h3>Considerations</h3><p>* <a href="https://devcenter.heroku.com/articles/free-dyno-hours#dyno-sleeping">https://devcenter.heroku.com/articles/free-dyno-hours#dyno-sleeping</a><br>** Optional<br>*** Only if you want SSL (HTTPS). If you don’t mind the HTTP address, you don’t need to change the plan.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1217d7b66cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criar um site estático utilizando HUGO no Heroku]]></title>
            <link>https://matheusvt.medium.com/criar-um-site-est%C3%A1tico-utilizando-hugo-no-heroku-c9593828fe70?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9593828fe70</guid>
            <category><![CDATA[site]]></category>
            <category><![CDATA[godaddy]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[hugo]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 21:12:02 GMT</pubDate>
            <atom:updated>2022-06-06T22:49:43.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Como criar um site estático utilizando HUGO no Heroku</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*m9FfgXpsD7bgya-MVgApuQ.png" /><figcaption>Logos do HUGO e Heroku.</figcaption></figure><h3>Intro</h3><p>Recentemente descobri o HUGO (<a href="https://gohugo.io/">https://gohugo.io/</a>), um gerador de sites estáticos, escrito em Go e de fácil utilização. A grande vantagem de utilizar o HUGO é a velocidade e praticidade para criar sites e blogs pessoais.</p><p>Com o site gerado, vem a pergunta, onde hospedar? Aí que entra o Heroku (<a href="https://www.heroku.com/">https://www.heroku.com/</a>), um serviço de hospedagem de aplicações, em nuvem. O mais interessante dessa plataforma é que ela oferece entre 550–1,000 horas* de hospedagem grátis por mês, ou seja, não será necessário pagar para hospedar seu site.</p><p>Atualmente o Heroku não suporta o uso direto do HUGO, então para contornar esse problema, iremos criar uma imagem Docker com as configurações necessárias para que ele seja inicializado pelo Heroku.</p><h3>Pré requisitos</h3><p>Para realizar este tutorial, você precisará de:</p><ul><li>Hugo — <a href="https://gohugo.io/getting-started/installing/">https://gohugo.io/getting-started/installing/</a></li><li>Conta no Heroku — <a href="https://id.heroku.com/login">https://id.heroku.com/login</a></li><li>CLI Heroku — <a href="https://devcenter.heroku.com/articles/heroku-cli#install-the-heroku-cli">https://devcenter.heroku.com/articles/heroku-cli#install-the-heroku-cli</a></li><li>Conta GitHub** — <a href="https://github.com/">https://github.com/</a></li><li>CLI Git — <a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">https://git-scm.com/book/en/v2/Getting-Started-Installing-Git</a></li><li>Docker — <a href="https://docs.docker.com/engine/install/">https://docs.docker.com/engine/install/</a></li></ul><h3>Passos</h3><ol><li>Criar um novo site pelo HUGO</li><li>Associar ao GitHub**</li><li>Criar app no Heroku</li><li>Baixar um tema do Hugo e alterar o <em>config.toml</em></li><li>Criar os arquivos <em>Dockerfile</em> e <em>heroku.yml</em></li><li>Testar o HUGO localmente**</li><li><em>Commitar</em> as mudanças</li><li>Subir a imagem para o Heroku</li><li><em>Push</em> das mudanças</li><li>Acesso ao site</li></ol><p>BONUS — Uso de domínio personalizado com SSL</p><h3>Hands-On</h3><h4>1. Criar um novo site pelo HUGO</h4><p>Primeiramente iremos criar um novo site pela linha de comando (<em>command-line interface</em> — CLI).</p><p>Abra o terminal do seu computador (cmd no windows, terminal no linux e mac) e vá para a pasta em que gostaria de criar seu site.</p><p>No meu caso, irei criar na pasta <em>Documents</em>.</p><p>Comandos:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c087226815bf93a5efe1a8d9c1824f4/href">https://medium.com/media/0c087226815bf93a5efe1a8d9c1824f4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*yh6MBLPZC-sBvG9Aa8GqMA.png" /><figcaption>Resposta do comando hugo new site myhugosite.</figcaption></figure><h4>2. Associar ao GitHub**</h4><p>Na pasta criada pelo HUGO, inicializar o git e associar ao repositório no GitHub, necessário criar antes de adicionar o <em>remote</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*JI-JInQcOdFjU_v8ii7sgg.png" /><figcaption>Exemplo de como criar repositório no github.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41762e4c1056668ba012c77e0de3466/href">https://medium.com/media/a41762e4c1056668ba012c77e0de3466/href</a></iframe><h4>3. Criar app no Heroku</h4><p>Para criar um app no Heroku, podemos utilizar tanto a interface gráfica quanto o CLI, neste caso, estou usando o CLI por ser mais simples. Tendo criado a conta no Heroku e instalado o CLI, basta inserir os comandos abaixo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebc12ed18a569ffdbbfb6f64ebd9df0e/href">https://medium.com/media/ebc12ed18a569ffdbbfb6f64ebd9df0e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*tBbWpeV6GkzDVEfGZsNUqw.png" /><figcaption>Resposta do comando heroku apps:create myhugosite.</figcaption></figure><p>Observe que estou me <em>logando</em> no Heroku, criando um app de nome <em>myhugosite </em>e associando ao repositório que o Heroku nos disponibiliza.</p><h4>4. Baixar um tema do Hugo e alterar o <em>config.toml</em></h4><p>Nesse passo, a sua pasta deve estar com a seguinte estrutura:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*2mrMLNLtw4DQjt8VpXY_Kw.png" /><figcaption>Estrutura do site criado pelo Hugo.</figcaption></figure><p>Caso não tenha realizado o passo 2, a diferença é que não terá os arquivos <em>README.md</em> e <em>.gitignore</em>.</p><p>Para esse tutorial, utilizaremos o tema <a href="https://github.com/StaticMania/hugo-cohub">hugo-cohub</a>, para escolher outros temas, basta visitar os sites <a href="https://jamstackthemes.dev/#ssg=hugo">https://jamstackthemes.dev/#ssg=hugo</a> ou <a href="https://themes.gohugo.io/">https://themes.gohugo.io/</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bf08bfcbe096d65032995cad7a0cf49/href">https://medium.com/media/2bf08bfcbe096d65032995cad7a0cf49/href</a></iframe><p>Pelo padrão do HUGO, os temas devem estar clonados na pasta <em>themes</em>, por isso estou passando o caminho <strong>themes/hugo-cohub</strong>. Observe que estou removendo o .git do repositório clonado, faço isso apenas para não ficar com referências de outros projetos.</p><p>Agora, vamos alterar o arquivo <em>config.toml</em> para o nosso projeto. Observe os campos <em>baseURL</em> e <em>theme</em>. Esses são importantes para o uso correto do tema, o primeiro refere à url gerada pelo heroku, o padrão é <strong>https://&lt;nomedoapp&gt;.herokuapp.com, </strong>neste caso a url é <a href="https://myhugosite.herokuapp.com./">https://myhugosite.herokuapp.com</a>. O segundo refere-se ao nome da pasta onde o tema se encontra, no caso é <em>hugo-cohub </em>(não precisa referenciar a pasta <em>themes</em>). As outras configurações são auto-explicativas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91381101df463c2f26113a4aa67197cd/href">https://medium.com/media/91381101df463c2f26113a4aa67197cd/href</a></iframe><h4>5. Criar os arquivos <em>Dockerfile</em> e <em>heroku.yml</em></h4><p>Iremos agora criar um arquivo chamado Dockerfile na raiz da pasta do projeto.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd06d4ed248fc225a50fdb3cc6efdf1/href">https://medium.com/media/9fd06d4ed248fc225a50fdb3cc6efdf1/href</a></iframe><p>Explicando: Estou utilizando a imagem <a href="https://hub.docker.com/layers/debian/library/debian/stable-slim/images/sha256-bfe148bd4647169a5597ac5e975ecd7809619ccda32b2b8eb909f05eeb14405b?context=explore">debian:stable-slim</a>, copiando todos os meus arquivos da pasta local (.) para a pasta /src. Após a cópia, inicio a instalação do hugo, limpo os arquivos desnecessários, crio o usuário <em>hugo</em>, utilizo o caminho /src como <em>default </em>do <em>container</em> e inicializo o Hugo.</p><p>O próximo passo é criar o <em>heroku.yml</em>, este é o arquivo que a plataforma irá se basear para executar as etapas de <em>build</em> e <em>run</em>. A documentação de como escrever um heroku.yml está disponível em:</p><p><a href="https://devcenter.heroku.com/articles/build-docker-images-heroku-yml">https://devcenter.heroku.com/articles/build-docker-images-heroku-yml</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56fd55a3a52f73bd3e44251b1b3b03ee/href">https://medium.com/media/56fd55a3a52f73bd3e44251b1b3b03ee/href</a></iframe><p>Explicando: O primeiro passo a ser executado é o <em>build</em> da imagem conforme o Dockerfile, damos o nome da imagem gerada de <em>web</em>. Na próxima etapa, de <em>run</em>, falamos para executar o comando na imagem <em>web</em>.</p><p>Argumentos:</p><p>bind=0.0.0.0 → Associa a interface de conexão para o servidor (default “127.0.0.1”), se não colocar na “0.0.0.0” o Heroku não conseguirá acessar o servidor.</p><p>port=$PORT → O Heroku associa uma porta aleatória para seu Dyno, mas disponibiliza esse valor como variável de ambiente (default “1313”).</p><p>appendPort=false → Caso não mude para <em>false</em>, as referências dos links virão com o número da porta, causando erro no direcionamento e acesso de links (default “true”).</p><p>baseURL=<a href="https://myhugosite.herokuapp.com/">https://myhugosite.herokuapp.com/</a> → hostname (e caminho) para a raiz do seu projeto, como estamos utilizando o Heroku, precismos atualizar conforme a URL que ele nos oferece.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuiX35PHr8jQRKa8AfVWfA.png" /><figcaption>Estrutura de arquivos.</figcaption></figure><h4>6. Testar o HUGO localmente**</h4><p>Para testar localmente iremos copiar os conteúdos das pastas do tema hugo-cohub/exampleSite para as pastas da estrutura gerada pelo Hugo. Após a cópia, basta iniciar o servidor com o comando hugo server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10ed8597b759ff97b9ee6adb862ff9f5/href">https://medium.com/media/10ed8597b759ff97b9ee6adb862ff9f5/href</a></iframe><p>Se tudo ocorrer bem, será possível acessar seu site localmente pelo endereço <a href="http://localhost:1313/">http://localhost:1313/</a></p><h4><em>7. Commitar</em> as mudanças</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6964a5851f4301b3db0495cbff840de/href">https://medium.com/media/f6964a5851f4301b3db0495cbff840de/href</a></iframe><h4>8. Subir a imagem para o Heroku</h4><p>Conforme a <a href="https://devcenter.heroku.com/articles/container-registry-and-runtime#getting-started">documentação do heroku</a>, para subir o <em>container</em> para o <em>registry</em> do Heroku, bastar realizarmos os comandos abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b47c7b953bd967a568fab83317d0449/href">https://medium.com/media/8b47c7b953bd967a568fab83317d0449/href</a></iframe><h4><em>9. Push</em> das mudanças</h4><p>Para realizar mudanças em seu site, basta salvar as mudanças localmente, <em>commitar</em> e realizar um push para o Heroku.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec41c35932026edf9e21282e6784bfe/href">https://medium.com/media/5ec41c35932026edf9e21282e6784bfe/href</a></iframe><p>Caso realizou o passo 2, podemos configurar o Heroku para realizar os <em>deploys </em>para cada <em>push</em> que realizar em uma <em>branch</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ls6t2o7S93S4leRpU6ORLw.png" /><figcaption>Configuração do deploy pelo GitHub.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdpe1UFex5wSXTa9CWrxoQ.png" /><figcaption>Habilitando o deploy automático para a branch main.</figcaption></figure><h4>10. Acesso ao site</h4><p>Para acessar o site basta esperar o build e deploy e acessar o link gerado pelo Heroku (<strong>https://&lt;nomedoapp&gt;.herokuapp.com) </strong>ou clickar no botão “Open app” na página Overview de seu app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKZLrZiPFH1sKT0KyDCi-A.png" /><figcaption>Página Overview do app no Heroku.</figcaption></figure><h4>Repositório de exemplo</h4><p><a href="https://github.com/matheusvt2/myhugosite">GitHub - matheusvt2/myhugosite</a></p><h3>BONUS — Uso de domínio personalizado com SSL</h3><h4>1. Compra do domíno</h4><p>É possível utilizar domínios de vários <em>registradores</em>, um exemplo famoso é o <a href="https://www.godaddy.com/">GoDaddy</a>, onde oferece domínios de vários tipos.</p><h4>2. Configuração do DNS do domínio</h4><p>Primeiro precisaremos adicionar um domínio pela aba Settings do seu app no Heroku, botão “Add domain”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxpoIcgjK7oWQAc81F5Mbg.png" /><figcaption>Configuração de domínio na aba Settings.</figcaption></figure><p>Agora basta copiar o “DNS Target” gerado e alterar o valor do CNAME nas configurações do DNS do seu domínio (GoDaddy por exemplo).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zJLdU0SGFxPnVtu1BzpQg.png" /><figcaption>Configuração do DNS no registrador (GoGaddy).</figcaption></figure><p>IMPORTANTE! → Ainda nas configurações de DNS, configurar o <em>Encaminhamento</em> ou <em>Forwarding </em>do tipo<em> permanente (301) </em>para o endereço do seu domínio, por exemplo: <a href="http://myhugosite.com/"><strong>http://myhugosite.com</strong></a><strong> </strong>ou<strong> </strong><a href="http://myhugosite.com/"><strong>https://myhugosite.com</strong></a><strong> </strong>caso realize o passo 4.</p><h4>3. Alteração do config.toml e heroku.yml</h4><p>Nos arquivos <em>config.toml</em> e <em>heroku.yml</em> alterar o valor de <strong>baseURL</strong> para o nome do seu domínio, por exemplo <strong>baseURL = ‘http://myhugosite.com/’ </strong>ou<strong> </strong><a href="http://myhugosite.com/"><strong>https://myhugosite.com/</strong></a><strong> </strong>caso realize o passo 4.</p><h4>4. Upgrade do Dyno para Hobby*** (7$ mensais).</h4><p>Para fazer o upgrade é necessário cadastrar seu cartão de crédito em Account Settings → Billing. Após configurar, basta alterar o plano do Dyno pela aba Resources do seu app de Free para Hobby.</p><p>Para habilitar o SSL é só selecionar “Automatic Certificate Management” (ACM) nas configurações de certificado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btIFhykNJ4p3r-36GttAmw.png" /><figcaption>Configuração de SSL.</figcaption></figure><h3>Considerações</h3><p>* <a href="https://devcenter.heroku.com/articles/free-dyno-hours#dyno-sleeping">https://devcenter.heroku.com/articles/free-dyno-hours#dyno-sleeping</a><br>** Opcional<br>*** Somente caso queira SSL (HTTPS). Caso não se importe com o endereço HTTP, não precisa alterar o plano.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9593828fe70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ambiente de desenvolvimento Docker no Visual Studio Code.]]></title>
            <link>https://matheusvt.medium.com/ambiente-de-desenvolvimento-docker-no-visual-studio-code-7a794e411a3?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a794e411a3</guid>
            <category><![CDATA[remote-containers]]></category>
            <category><![CDATA[visual-studio-code]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 03:02:03 GMT</pubDate>
            <atom:updated>2021-07-12T15:17:47.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*CR6LhJw0jVjpk3ty.png" /><figcaption>Logo do Docker e Visual Studio Code.</figcaption></figure><p>Quantas vezes você testou seu computador e quando fez um Pull/Merge request, a pipeline quebrou porque você esqueceu de referenciar o último pacote que instalou para implementar uma nova <em>feature?</em></p><p>Para evitar problemas assim, desenvolvi uma estratégia: sempre codificar dentro de um ambiente Docker e rodar os testes dentro dele. Isso é ótimo, mas é muito irritante ter que criar um container, nomeá-lo, anexar um volume, expor portas de serviço, todas as vezes.</p><p>Então, para aqueles que não estão familiarizados, o Visual Studo Code tem uma extensão chamada “Remote — Containers”, que facilita muito essa criação de ambiente, olhe só.</p><p><strong>Requisitos:</strong></p><ul><li>Visual Studio Code;</li><li>Docker;</li><li>Extensão Remote — Containers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H_gOcXrfFf62CoR4.png" /><figcaption>Extensão Remote — Containers.</figcaption></figure><p><strong>Prática:</strong></p><p>Se já instalou os requisitos, não tem segredo aqui, você só precisa criar seu Dockerfile e a lista de requisitos do seu projeto (neste exemplo, usamos python) dentro da pasta do projeto, como abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E943V0WbJS_GgAr-.png" /><figcaption>Exemplos do Dockerfile e da lista de requisitos.</figcaption></figure><p>Depois, usando a extensão remote-containers, selecione uma pasta para abrir dentro do container (note que eu não estou anexando nenhum volume manualmente).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*uxM2D-VTp0zyiOCV.png" /><figcaption>Aperte F1 para procurar a extensão.</figcaption></figure><p>Escolha a opção Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*3FqYm422Blz4eVPY.png" /><figcaption>Seleção do arquivo de configuração.</figcaption></figure><p>Eeeee, é isso, seu ambiente logo será criado com todos os requisitos listados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*z3pOHHj3nKfjxJtc.png" /><figcaption>Build da imagem.</figcaption></figure><p>Agora você pode rodar os testes e nunca mais dizer: “mas na minha máquina funciona”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rkbnyIrFFY8Yznyj.png" /><figcaption>Rode comandos dentro do container.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Ca2pjHv53EapPaSe.png" /><figcaption>Portas são criadas automaticamente.</figcaption></figure><p>É isso por hoje. Espero que ajude.</p><p><em>OBS. é possível instalar extensões do Visual Studio Code dentro do novo ambiente de testes “containerizado”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*6impKf6LQ7Ottx-5.png" /><figcaption>Instalando o Code Runner no container de dev.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/0*-JsoeGVrwlgKQnzB.png" /><figcaption>Extensões locais e no ambiente de dev.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a794e411a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker development environment on Visual Studio Code.]]></title>
            <link>https://matheusvt.medium.com/docker-development-environment-on-visual-studio-code-5b7aafbe285c?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b7aafbe285c</guid>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[remote-containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 02:56:53 GMT</pubDate>
            <atom:updated>2021-07-12T03:02:03.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*ACoCpeW7P58-czsLjamI4Q.png" /><figcaption>Visual Studio Code and Docker logos.</figcaption></figure><p>How many times have you tested your code on your machine and when you Pull/Merge request, the pipeline breaks because you missed the last package that you installed to implement a new feature?</p><p>To avoid issues like that I developed a strategy, to always code inside a docker environment and run my tests inside of it. That’s great, but it’s annoying creating a container, name it, attach a volume, expose a port, every time.</p><p>So, for those who are unfamiliar, Visual Studio Code has an extension called “Remote - Containers”, that makes it much easier, check it out.</p><p><strong>Requirements:</strong></p><ul><li>Visual Studio Code;</li><li>Docker;</li><li>Remote - Containers extension.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukV2RLdQYa50XXTPA3bk7g.png" /><figcaption>Remote — Containers extension.</figcaption></figure><p><strong>Hands-On:</strong></p><p>If you already installed the requirements, that’s no secret here, you just need to create your Dockerfile and the requirements list (e.g for python) inside your project folder, just like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUOrBpgLTRpcOvmo3_wfIQ.png" /><figcaption>Dockerfile and requirements examples.</figcaption></figure><p>Then, using the remote-containers extension select a folder to open in a container (notice here that i’m not attaching any volume).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DVrXe6opykG68xmYUhjcqA.png" /><figcaption>Type F1 and find remote-containers extension.</figcaption></figure><p>Choose the Dockerfile option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*DYpIjvlS0xlxvo__fVE0tg.png" /><figcaption>Configuration files selection.</figcaption></figure><p>Aaaaand, that’s it, your environment soon will be created with all your requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOBQOdvLPY-3ZbzXCPOdGw.png" /><figcaption>Image build.</figcaption></figure><p>Now you can run tests and never say again: “but it works on my machine”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlc0s84c8MJg-DyjZZoOwA.png" /><figcaption>Run commands inside the docker container.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Um6xiQo9yMhrW7xivw3qyw.png" /><figcaption>Ports are automatically created.</figcaption></figure><p>That’s it for today. Hope it helps.</p><p><em>P.S. it is possible to install Visual Studio Code extensions inside the new containerized environment.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*71f7drwnUv2wr5Dau2ihdA.png" /><figcaption>Installing Code Runner in Dev Container.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*7CLufJZK8m3kJObBlg6j-A.png" /><figcaption>Local and Dev (container) VS Code installed extensions.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b7aafbe285c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a decoupled ML model from its application on AWS]]></title>
            <link>https://awstip.com/deploying-a-decoupled-ml-model-an-application-on-aws-31dfd44beaa3?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/31dfd44beaa3</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[decoupled]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Sun, 04 Apr 2021 17:58:41 GMT</pubDate>
            <atom:updated>2021-04-05T13:42:05.230Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As a data scientist and a DevOps enthusiast, I was searching for a way to deploy a Machine Learning app decoupled from its model because I was struggling to use embedded models due to massive container sizes. Imagine adding a 3GB neural network model inside a container image!!! That’s a huge infrastructure problem.</p><p>Browsing on internet, I found the following article about a concept called CD4ML.</p><p><a href="https://martinfowler.com/articles/cd4ml.html">Continuous Delivery for Machine Learning</a></p><p>That definitely caught my attention. Decoupling a model from its app results on several advantages:</p><ul><li>Front End developers can deploy new features independently from the DataScience team.</li><li>It’s possible to train, save and change model versions without stopping the service.</li><li>Reduce app size.</li><li>Reduce registry usage.</li><li>Reduce deployment complexity.</li><li>Reduce time to change model version or type.</li></ul><p>Drawbacks:</p><ul><li>More complex to implement.</li><li>Developer must implement ways to deal with connection problems between services.</li></ul><h3>Main objective</h3><p>In this article I’ll not cover how to configure the Amazon Services because there are good tutorials on internet (and I’ll post below). The main objective is to test a functional Machine Learning application that loads a model from an API. In this case, we are going to predict the variety of Iris flower based on four predictor variables. Yes, I’m using the (<em>in)</em>famous Iris dataset.</p><h3>Prerequisites</h3><ul><li>AWS account — <strong>May be some costs, be aware!</strong></li><li>8 GB RAM / 100 GB Disk linux laptop.</li><li>Application and Model.</li></ul><p>All the files used on this experiment are available in my repository on github.</p><p><a href="https://github.com/matheusvt2/cd4ml">matheusvt2/cd4ml</a></p><h3>Architecture</h3><p>After some research, I found plausible the following architecture for a CD4ML project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkxUHNCK_LDBR_pYAYHr9w.png" /><figcaption>CD4ML architecture.</figcaption></figure><h4>- Application pipeline</h4><p>A CI/CD pipeline using CodePipeline to build a container after triggered by a pull request on CodeCommit, deploying on EKS (or ECS) service.</p><h4>- Data pipeline</h4><p>Amazon offers a wide range of services to stream, extract, transform and load data. We can use Kinesis Data Streams (Kafka like) to stream events, apply a Lambda function to transform the data and use Data Firehose to transfer the data to Amazon Redshift (data warehouse).</p><h4>- Experimentation</h4><p>SageMaker is a great solution for data modeling and exploration. It’s possible to connect with S3 to save and load artifacts.</p><h4>- Model serving</h4><p>I’ll use<em> </em><a href="https://mlflow.org/"><em>mlFlow</em></a><em> </em>server to manage and serve our trained models. Needs connection to amazon S3 to save run artifacts and a SQL to save metadata.</p><h3>Real architecture used on this experiment</h3><p>To reduce costs and complexity, I changed some services and removed others, resulting in the following architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnoSVRa7nCDnntrIhv-A7A.png" /><figcaption>Experiment architecture.</figcaption></figure><p>Note that our data is on my personal laptop, together with the Jupyter notebook server. The data is available <a href="https://github.com/matheusvt2/cd4ml/tree/main/data">here</a>. All the data pipeline was removed.</p><p>I changed the EKS service to an EC2 instance, deploying an <em>ad-hoc</em> docker container. Also changed ECR for DockerHub.</p><p>For a better understanding, I’ll split the experiment into four parts:</p><ul><li>Part I: CI/CD pipeline to delivery a Flask application.</li><li>Part II: MlFlow connection with S3 and MySQL database.</li><li>Part III: Jupyter integration with MlFlow.</li><li>Part IV: Model decoupling.</li></ul><h3>Part I — CI/CD Pipeline</h3><p>First of all, I created a project on CodeCommit, <a href="https://docs.aws.amazon.com/pt_br/codecommit/latest/userguide/setting-up-https-unixes.html">configured my git</a> and pushed my <a href="https://github.com/matheusvt2/cd4ml/tree/main/app">app</a> folder including appspec.yml (for CodeDeploy), buildspec.yml (for CodeBuild), dockerfile and requirements.txt files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UM7qtBpfNZIBBMC_049y8w.png" /><figcaption>CodeCommit.</figcaption></figure><p>After creating the repository, I created the CodePipeline. For those who are not familiar with it, I suggest watching this great video on youtube.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkaZOF4EEPqk&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkaZOF4EEPqk&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FkaZOF4EEPqk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b847db7f8bde4a48e414548b0e546620/href">https://medium.com/media/b847db7f8bde4a48e414548b0e546620/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aFr2twSEhiGu9NmexjQAg.png" /><figcaption>CodePipeline.</figcaption></figure><p>I used as reference the following article on medium to make my app web page. I modified the model loading (to mlflow URI, instead of local) and added a new route “/model/” to return the current model used by the application.</p><p><a href="https://medium.com/@nutanbhogendrasharma/deploy-machine-learning-model-with-flask-on-heroku-cd079b692b1d">Deploy Machine Learning Model with Flask on Heroku</a></p><h3>Part II — Mlflow</h3><p>For this, I used a modified Image with mlFlow to speed up the process.</p><p><a href="https://github.com/matheusvt2/mlflowserver">matheusvt2/mlflowserver</a></p><p>I connected to two different ECS instances and run one command on each one:</p><p>First EC2:</p><p>docker run -d — name mysql -e MYSQL_ROOT_PASSWORD=root -e MYSQL_TCP_PORT=3306 -p 3306:3306 mysql:latest mysqld — default-authentication-plugin=mysql_native_password</p><p>Second EC2:</p><p>docker run -it — rm — name mlflow -p 5000:5000 -e BACKEND_URI=mysql+pymysql://root:root@&lt;EC2_INTERNAL_IP&gt;:3306/mlflow — e AWS_ACCESS_KEY_ID=&lt;ACCESS_KEY_ID&gt; -e AWS_SECRET_ACCESS_KEY=&lt;SECRET_ACCESS_KEY&gt; -e MLFLOW_PORT=5000 -e ARTIFACT_ROOT=s3://&lt;BUCKET-NAME&gt;/mlflow/ matheusvt/mlflowserver:1.12.1</p><h3>Part III — Jupyter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-ovHCd4Uh0bXeHvu6GBAQ.png" /><figcaption>MlFlow connection on Juyter Notebook.</figcaption></figure><p>*It’s important to remember that you’ll need to set your credentials as environments variables to connect with S3 to save your model.</p><blockquote>MLflow obtains credentials to access S3 from your machine’s IAM role, a profile in ~/.aws/credentials, or the environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY depending on which of these are available.</blockquote><h3>Part IV — Model decoupling</h3><p>First, I deployed my app using the configured pipeline after a push into my CodeCommit repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QwLBsVEc7HSSxltsUf0qQ.png" /><figcaption>Application pipeline.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BG4W725jr_uIzFdHz3JkQ.png" /><figcaption>Pushed image to my registry by CodeBuild.</figcaption></figure><p>Later, using my Jupyter notebook server running on my laptop, I trained some Random Forest Classifiers (sklearn) and saved their runs using MlFlow API, as is possible to check on this <a href="https://github.com/matheusvt2/cd4ml/blob/main/experimentation.ipynb">notebook</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipWm4InLHzjFrWVtF7_opg.png" /><figcaption>MlFlow experiment runs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dimE4F8Fcy7JA8fd6Zh2tQ.png" /><figcaption>Mlflow Models.</figcaption></figure><p>Now, let’s use our web site to predict which specie of Iris Flower is, given the predictor variables Sepal length, Sepal width, Petal length and Petal width.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFYDlq5dIExmPOoc_jJX3A.png" /><figcaption>Home page on app.</figcaption></figure><p>The prediction result is… Setosa!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9J03VNDHUc28sztD1RV0Q.png" /><figcaption>Prediction result on app.</figcaption></figure><p>Now, let’s check which model version we’re using to predict the correct flower. Browsing on “/model/” route is possible to verify that the current version is the 13th, same as in production on MlFlow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDx0sJ_M27oC84X99kiAZg.png" /><figcaption>Production model (Version 13) on MlFlow and on app.</figcaption></figure><p>Now, lets change the production model to the 8th version using MlFlow UI and check again in “/model/” route. Great! Worked as expected, now we’re using the 8th version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRswcg69to-lgGQ2fPhG4w.png" /><figcaption>Changed production model (Version 8) on MlFlow and on app.</figcaption></figure><h3>Conclusions</h3><p>AWS can easily attend all the needs we have to deploy a decoupled machine learning model from it’s app. The solution works as expected and performs really well.</p><p>Problems found:</p><ul><li>Lack of built-in user access control/permission on mlFlow. We can use a load balancer (nginx) to control who is able to access, but not the user roles.</li><li>Usage of AWS credentials inside the container for saving models and artifacts on S3 bucket. This can be solved using EKS + Secrets Manager.</li><li>The developer / data scientist must handle when to load the model. Ex.: first check if the current loaded model is the same as in production (from MlFlow), if diferent, load.</li></ul><p>Although these problems, I’ll consider implement this structure on new projects, it really worth while.</p><p>See you on next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31dfd44beaa3" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/deploying-a-decoupled-ml-model-an-application-on-aws-31dfd44beaa3">Deploying a decoupled ML model from its application on AWS</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Subindo o Bitnami Harbor em um cluster Kubernetes local.]]></title>
            <link>https://matheusvt.medium.com/subindo-o-bitnami-harbor-em-um-cluster-kubernetes-local-510d5e82a224?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/510d5e82a224</guid>
            <category><![CDATA[local]]></category>
            <category><![CDATA[notebook]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[bitnami]]></category>
            <category><![CDATA[harbor]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 19:05:42 GMT</pubDate>
            <atom:updated>2021-03-22T16:19:45.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*B21ExgxOQCSUT3tGMz68WQ.png" /><figcaption>Logo do Bitnami Harbor.</figcaption></figure><h3>Introdução</h3><p>Por anos tenho usado o Bitnami para imagens de container e VMs para implantar apps para fins de estudo, porque eles realmente fazem um ótimo trabalho simplificando o seu uso, mas este foi um caso atípico. Por esse motivo, decidi escrever um guia de instalação passo a passo.</p><p><strong>Bitnami Harbor:</strong></p><p><a href="https://bitnami.com/stack/harbor/helm">Harbor</a></p><p><strong>Informação do Sistema:</strong></p><ul><li>8 GB RAM</li><li>I5 CPU</li><li>100 GB de disco</li><li>Ubuntu 20.10</li></ul><h3>Pré-requisitos</h3><ul><li><a href="https://snapcraft.io/docs/installing-snap-on-ubuntu">Snap</a></li><li>Kubernetes Cluster (microk8s, minikube, K3s) — Neste guia estou usando o <a href="https://microk8s.io/docs">microk8s</a>.</li><li>Kubedns (microk8s enable dns)</li><li><a href="https://helm.sh/docs/intro/install/">Helm</a></li></ul><p>Os processos de instalação dos programas acima são bem fáceis, é só seguir a documentação que não tem erro.</p><h3>Verificalção do Kubernetes</h3><p>Espere pela inicialização do microk8s. É possível verirficar o status usando o comando abaixo.</p><pre>bash# microk8s status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*wJBhqFcRosp0qi02vSpzZQ.png" /><figcaption>Saída do comando microk8s status.</figcaption></figure><p>Agora que verificamos que o microk8s está rodando, vamos verificar se existe algum pod no namespace default. Você deve ter a saída “No resources found in default namespace.”</p><pre>bash# kubectl get pods</pre><h3>Configuração do Bitnami Harbor</h3><p>Depois de instalar o helm, e usuá-lo para instalar o Harbor, verifique novamente os pods.</p><pre>bash# helm install my-release bitnami/harbor</pre><pre>bash# kubectl get pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*8w5Kgtz1Ae-YIvf9zv4XDg.png" /><figcaption>Saída do comando kubectl get pods.</figcaption></figure><p>Observe que alguns pods não conseguem incializar, vamos verificar o PVC (Persistent Volume Claim):</p><pre>bash# kubectl get pvc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bWQ70lzcOdOVU9j7P9jp_Q.png" /><figcaption>Saída do kubectl get pvc.</figcaption></figure><p>Este é o problema, não existe nenhum PV (Persistent Volume) para ser requisitado pelo PVC. Então vamos criá-los.</p><pre>bash# kubectl apply -f pv.yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f4f4f3b62ccee4c44d02853b9e1092/href">https://medium.com/media/a7f4f4f3b62ccee4c44d02853b9e1092/href</a></iframe><p>Agora vamos verificar novament o PVC e os pods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*1v8hybOnq5Wq4OmCW5Bxtg.png" /><figcaption>Saída do comando kubectl get pvc.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*mrrVgQb2wmcMnCXJqCTWbg.png" /><figcaption>Saída do comando kubectl get pods.</figcaption></figure><p>Tudo pronto, agora veja que os PVCs estão ligados aos PVs criados e todos os pods estão rodando.</p><h3>IP de acesso e configuração inicial</h3><p>Para acessar a interface do Harbor, você tem que achar o IP do serviço do LB (Load Balancer), para tal, é só dar o seguinte comando.</p><pre>bash# kubectl get svc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*EkKgfItc_AZ0DUxhT5Z-Uw.png" /><figcaption>Saída do comando kubectl get svc.</figcaption></figure><p>Ótimo! Agora que temos o IP, é só navegar. Eu não vou mostrar como pegar a senha de admin porque já está bem documentado pelo Bitinami.</p><p>Agora vamos criar um projeto “handson” e um usuário “matheus”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umnok0mYPrPZ8qQsamtfuQ.png" /><figcaption>Projeto de nome handson e usuário matheus.</figcaption></figure><p>Vamos tentar nos logar, usando o comando abaixo.</p><pre>bash# docker login 10.152.183.168</pre><p>Oh não! Um erro ocorreu. Essa é a parte que demorei para resolver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*dT8QRC9FahKYw7U5MjSCuQ.png" /><figcaption>Saída do comando docker login 10.152.183.168.</figcaption></figure><p>Este erro é por causa que o certificado não está configurado para IP (precisa ser CN = CN=*.example.com) E o certificado não é valido. Para resolver esses problemas nós temos que seguir os seguintes passos:</p><p>1º — Faça o Download do certificado pelo navegador.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*rX0TneYd7ldksWE9sOHefw.png" /><figcaption>Screenshot da aba Details do Certificate Viewer do Chrome.</figcaption></figure><ul><li>2º — Edite o arquivo /etc/hosts, incluindo a linha 10.152.183.168 core.harbor.domain (para resolver o nome para um IP — de sua máquina local somente). Eu preciso fazer isso porque não tenho um domínio nem um servidor DNS.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*n4_A8QiYCjRAKiRNzUX8LQ.png" /><figcaption>Arquivo /etc/hosts.</figcaption></figure><ul><li>3º— Agora, sob /etc/docker, crie um novo diretório chamado certs.d, e dentro dele, crie um outro diretório chamado core.harbor.domain. Dentro de core.harbor.domain copie o ca.crt do certificado raíz do registry.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7DkagUGy_e5mIq7oqD9zg.png" /><figcaption>Screenshot do System Setting no Harbor. O ca.cert pode ser baixado no link Download (Registry root Certificate).</figcaption></figure><p>Depois do terceiro passo, você deve ter essa estrutura de arquivos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*zv3SK2iWW_8jriWabOAhbA.png" /><figcaption>Estrutura do diretório /etc/docker.</figcaption></figure><p>Agora vamos tentar nos logar de novo, agora apontando para core.harbor.domain.</p><pre>bash# docker login core.harbor.domain</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*9GBPhTpxnyJQk8kitn5cZQ.png" /><figcaption>Saída do comando docker login core.harbor.domain.</figcaption></figure><p>Voilá! Agora é possível dar push para o registry do Harbor, vamos tentar dar um push da imagem hello-world para o projeto “handson” criado antes.</p><pre># docker tag hello-world core.harbor.domain/handson/hello-world<br># docker push core.harbor.domain/handson/hello-world</pre><pre>The push refers to repository [core.harbor.domain/handson/hello-world]</pre><pre>f22b99068db9: Pushed</pre><pre>latest: digest: sha256:1b26826f602946860c279fce658f31050cff2c596583af237d971f4629b57792 size: 525</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUxzn2USoJGXP7-6CkGy_w.png" /><figcaption>Imagem enviada ao projeto “handson”.</figcaption></figure><p>É isso, espero que ajude!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510d5e82a224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Bitnami Harbor on local Kubernetes cluster]]></title>
            <link>https://awstip.com/deploying-bitnami-harbor-on-local-kubernetes-cluster-9f6ff9acbdc7?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f6ff9acbdc7</guid>
            <category><![CDATA[laptop]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[harbor]]></category>
            <category><![CDATA[bitnami]]></category>
            <category><![CDATA[local]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 18:36:03 GMT</pubDate>
            <atom:updated>2021-04-01T20:16:02.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*B21ExgxOQCSUT3tGMz68WQ.png" /><figcaption>Bitnami Harbor logo.</figcaption></figure><h3>Introduction</h3><p>For years I’ve been using <a href="https://bitnami.com/">Bitnami’s</a> VMs and container images to deploy appliances for study purposes, because they really do a great job simplifying the usage, but this one was an outlier. For this reason, I’ve decided to write a step-by-step installation guide.</p><p><strong>Bitnami Harbor:</strong></p><p><a href="https://bitnami.com/stack/harbor/helm">Harbor</a></p><p><strong>System info:</strong></p><ul><li>8 GB RAM</li><li>I5 CPU</li><li>100 GB Disk</li><li>Ubuntu 20.10</li></ul><h3>Prerequisites</h3><ul><li><a href="https://snapcraft.io/docs/installing-snap-on-ubuntu">Snap</a></li><li>Kubernetes Cluster (microk8s, minikube, K3s) — In this case i’m using <a href="https://microk8s.io/docs">microk8s</a>.</li><li>Kubedns (microk8s enable dns)</li><li><a href="https://helm.sh/docs/intro/install/">Helm</a></li></ul><p>Just follow the installation instructions. There is no secret here.</p><h3>Check Kubernetes environment</h3><p>Wait for microk8s start, it is possible to check the status by using the following command.</p><pre>bash# microk8s status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*wJBhqFcRosp0qi02vSpzZQ.png" /><figcaption>Output from microk8s status.</figcaption></figure><p>Then, check for pods. You should get the output “No resources found in default namespace.”</p><pre>bash# bubectl get pods</pre><h3><strong>Bitnami Harbor configuration</strong></h3><p>After helm installation, and harbor installation, try checking the pods again.</p><pre>bash# helm install my-release bitnami/harbor</pre><pre>bash# kubectl get pods</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*8w5Kgtz1Ae-YIvf9zv4XDg.png" /><figcaption>Output from kubectl get pods.</figcaption></figure><p>Note that some pods can’t start, lets check the PVC (Persistent Volume Claim):</p><pre>bash# kubectl get pvc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bWQ70lzcOdOVU9j7P9jp_Q.png" /><figcaption>Output from kubectl get pvc.</figcaption></figure><p>That’s the problem, there is no PV (Persistent Volume) to be claimed. So, let’s create them.</p><pre>bash# kubectl apply -f pv.yaml</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f4f4f3b62ccee4c44d02853b9e1092/href">https://medium.com/media/a7f4f4f3b62ccee4c44d02853b9e1092/href</a></iframe><p>Now lets check again the PVC and PODs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*1v8hybOnq5Wq4OmCW5Bxtg.png" /><figcaption>Output from kubectl get pvc.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*mrrVgQb2wmcMnCXJqCTWbg.png" /><figcaption>Output from kubectl get pods.</figcaption></figure><p>All set, now all the PVCs are bounded to a PV and the PODs are running.</p><h3>Access IP and initial configuration</h3><p>To access Harbor UI, you just have to find the IP from the LB (Load Balance) service, to do so, just enter the following command.</p><pre>bash# kubectl get svc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*EkKgfItc_AZ0DUxhT5Z-Uw.png" /><figcaption>Output from kubectl get svc.</figcaption></figure><p>Great! Now we have the IP, just browse it. I’ll not show how to get the admin password because it’s covered on bitnami documentation.</p><p>Now we will create an user and a Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umnok0mYPrPZ8qQsamtfuQ.png" /><figcaption>Project named handson and user matheus.</figcaption></figure><p>Lets try to login, using the command:</p><pre>bash# docker login 10.152.183.168</pre><p>Oh no! An error occurred. That’s the tricky part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*dT8QRC9FahKYw7U5MjSCuQ.png" /><figcaption>Output from docker login 10.152.183.168.</figcaption></figure><p>That error is due the certificate is not set for IP (must be CN — CN=*.example.com) AND is not valid to our machine. To solve those problems we have to do the following steps:</p><ul><li>1st — Download the certificate from browser.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*rX0TneYd7ldksWE9sOHefw.png" /><figcaption>Screenshot from Details from Certificate Viewer on Chrome.</figcaption></figure><ul><li>2nd — Edit the file /etc/hosts, including the line 10.152.183.168 core.harbor.domain (to resolve the name to an IP). I need to do this because I don’t have a domain nor a DNS server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*n4_A8QiYCjRAKiRNzUX8LQ.png" /><figcaption>/etc/hosts file.</figcaption></figure><ul><li>3rd — Now under /etc/docker, create a new directory named certs.d, and inside it, create a new one named core.harbor.domain. Inside of core.harbor.domain copy the ca.crt of the registry root certificate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m7DkagUGy_e5mIq7oqD9zg.png" /><figcaption>Screenshot from System Setting on Harbor. The ca.cert can be downloaded by clicking on Download link (Registry root Certificate).</figcaption></figure><p>After the step 3, you should get this file structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*zv3SK2iWW_8jriWabOAhbA.png" /><figcaption>/etc/docker file structure.</figcaption></figure><p>Let’s try to login, now pointing to core.harbor.domain.</p><pre>bash# docker login core.harbor.domain</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*9GBPhTpxnyJQk8kitn5cZQ.png" /><figcaption>Output from docker login core.harbor.domain.</figcaption></figure><p>Voilà! Now it is possible to push to Harbor registry, let’s try to push the image hello-world to the project “handson” created before.</p><pre># docker tag hello-world core.harbor.domain/handson/hello-world<br># docker push core.harbor.domain/handson/hello-world</pre><pre>The push refers to repository [core.harbor.domain/handson/hello-world]</pre><pre>f22b99068db9: Pushed</pre><pre>latest: digest: sha256:1b26826f602946860c279fce658f31050cff2c596583af237d971f4629b57792 size: 525</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUxzn2USoJGXP7-6CkGy_w.png" /><figcaption>Image pushed to “handson” project.</figcaption></figure><p>That’s it. Hope it helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f6ff9acbdc7" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/deploying-bitnami-harbor-on-local-kubernetes-cluster-9f6ff9acbdc7">Deploying Bitnami Harbor on local Kubernetes cluster</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explicando passo a passo um arquivo Jenkinsfile]]></title>
            <link>https://matheusvt.medium.com/explicando-passo-a-passo-um-arquivo-jenkinsfile-e2afb475660?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2afb475660</guid>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[structure]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Fri, 28 Feb 2020 23:30:25 GMT</pubDate>
            <atom:updated>2020-02-28T23:45:33.462Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2v3OvpWtgs9rDX6aVWHyg.png" /></figure><p>Há uns meses atrás fiz uma publicação sobre criação de uma esteira CI/CD para Python usando o Jenkins (link abaixo), mas não foi explicado como escrever um <em>pipeline</em> como código. Nesta publicação tentarei explicar as diferenças entre <em>pipelines </em>(<em>Scripted </em>vs <em>Declarative) </em>e os blocos, seções e diretivas mais usuais.</p><p><a href="https://medium.com/@matheusvt/cria%C3%A7%C3%A3o-de-uma-esteira-ci-cd-para-python-usando-o-jenkins-afe47b9acd22">Criação de uma esteira CI/CD para Python usando o Jenkins</a></p><h3><strong><em>Scripted </em>vs <em>Declarative</em></strong></h3><p>O <em>pipeline </em>do tipo <em>Scripted </em>foi o primeiro a ser implementado como código pelo Jenkins, escrito em <a href="http://groovy-lang.org/"><em>groovy </em></a>e tem como propósito ser uma estrutura de fácil adaptação pelo usuário, sendo de responsabilidade do desenvolvedor criar a estrutura lógica do <em>pipeline</em>.</p><p>Para simplificar a vida do engenheiro DevOps, foi criado posteriormente o <em>pipeline </em>do tipo <em>Declarative,</em> também escrito em <em>groovy, </em>mas com uma estrutura definida, e é justamente esse tipo que iremos desbravar aqui.</p><p>Outras diferenças entre estes tipos de escrita são bem descritas no link abaixo.</p><p><a href="https://www.edureka.co/community/54705/difference-between-declarative-pipeline-scripted-pipeliine">what is the key difference between Declarative pipeline and scripted pipeliine</a></p><h3>Desmembrando o Pipeline</h3><p>Caso queira estudar a fundo todas as partes de um <em>pipeline</em>, recomendo a leitura da documentação oficial do Jenkins.</p><p><a href="https://jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline">Pipeline Syntax</a></p><p>TODOS os <em>pipelines </em>do tipo <em>Declarative </em>começam com um bloco chamado <strong><em>pipeline</em></strong>, como dito no tópico anterior, é necessário seguir com uma estrutura.</p><pre>pipeline {<br>    /* insert Declarative Pipeline here */<br>}</pre><h3>Sections</h3><h4><strong>Agent</strong></h4><p>O <em>agent</em> (computador) nada mais é onde será executado o seu <em>pipeline</em>, no caso descrito abaixo, configuramos o <em>agent </em>como <strong>any</strong>, ou seja, qualquer <em>agent </em>disponível será escolhido. Caso passe como parâmetro um <em>label</em>, escolhemos assim onde será realizada a execução do <em>pipeline</em>.</p><p>Temos dois tipos de <em>agent</em>, o <em>Top Agent </em>e o<em> Stage Agent</em>, a diferença é que se declarado no começo do <em>pipeline</em>, fora dos <em>stages</em>, as opções são carregadas depois de entrar no <em>agent</em>, já se declarado no <em>stage</em>, as opção serão carregadas antes do <em>agent</em>, verificando qualquer condição <em>when, </em>quando existentes.</p><pre>pipeline {<br>    agent any<br>}</pre><p>Parâmetros do <em>agent</em>: <strong>any, none, label, docker, dockerfile e kubernetes.</strong></p><h4>Post</h4><p>O bloco <em>post </em>define uma ou mais ações a serem executadas no final do <em>pipeline </em>ou do <em>stage, </em>dependendo de onde estiver declarado. O bloco <em>post </em>aceita qualquer uma das seguintes <em>post-conditions</em>: <strong>always</strong>, <strong>changed</strong>, <strong>fixed</strong>, <strong>regression</strong>, <strong>aborted</strong>, <strong>failure</strong>, <strong>success</strong>, <strong>unstable</strong>, <strong>unsuccessful</strong>, e <strong>cleanup</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39cf3d385eccffd83fcb3addb4401cc0/href">https://medium.com/media/39cf3d385eccffd83fcb3addb4401cc0/href</a></iframe><h4>Stages</h4><p>Contém uma sequência de diretivas do tipo s<em>tage. </em>É recomendado ter pelo menos uma diretriz<em> stage. </em>Simples assim.</p><h4>Steps</h4><p>A seção <em>steps </em>define um ou mais <em>steps</em> a serem executados em um <em>stage</em>.</p><p><strong>Script</strong></p><p>Aqui é onde temos a liberdade de realizar um trecho de um <em>pipeline </em>do tipo <em>Scripted</em> dentro do <em>pipeline </em>do tipo <em>Declarative</em>. Isso dá um poder enorme ao desenvolvedor DevOps. No exemplo abaixo utilizamos condicional <em>if</em> para tomar uma ação.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6834b2ec7e36c3deaf2daeb8243d0987/href">https://medium.com/media/6834b2ec7e36c3deaf2daeb8243d0987/href</a></iframe><h3>Directives</h3><h4>environment</h4><p>Assim como o <em>agent</em>, o <em>environment</em> pode ocorrer como uma diretiva global, se for escrito fora do <em>step</em>, ou dentro do <em>step</em>, seguem abaixo as duas condições.</p><p>Global:</p><pre>environment { <br>             PATH=&quot;/home/bitnami/miniconda3/bin:$PATH&quot;  <br>}</pre><p>Local:</p><pre>stages {<br>        stage(&#39;Load Parameters&#39;) {<br>            environment { <br>                PATH=&quot;/home/bitnami/miniconda3/bin:$PATH&quot;) <br>            }<br>     }<br>}</pre><h4>options</h4><p>A diretiva <em>options </em>permite configurar opções específicas do <em>pipeline </em>de dentro do próprio <em>pipeline</em>. Não entraremos a fundo aqui.</p><h4>parameters</h4><p>Provê uma lista de parâmetros consumíveis pelo <em>pipeline</em> que o usuário deve prover ao iniciar a execução do <em>pipeline</em>. Não entraremos a fundo aqui.</p><h4>triggers</h4><p>Como seu <em>pipeline </em>receberá o <em>trigger</em>, pode-se configurar recorrência temporal, mas para projetos configurados com um <em>webhook </em>a partir do SCM, não é necessário configurá-lo.</p><h4>stage</h4><p>Uma das diretivas mais importantes, aqui é configurado a etapa do seu <em>pipeline</em>, e está sempre contida dentro do bloco <strong><em>stages</em>.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adb16a2ca82384e1966b65717e0c195d/href">https://medium.com/media/adb16a2ca82384e1966b65717e0c195d/href</a></iframe><h4>input</h4><p>Ao utilizar essa diretiva, o <em>stage </em>irá aguardar a devolutiva do usuário. Importante caso necessite de aprovação para seguir com o <em>pipeline</em>. Não entraremos a fundo aqui.</p><h4>when</h4><p>Esta diretiva permite ao <em>pipeline </em>selecionar qual <em>stage </em>deve ser executado, baseado em condições. No exemplo abaixo vemos que existe uma validação por expressão regular no nome da <em>branch</em>, além de uma condição aninhada (<em>anyOf</em>).</p><pre>stage(&#39;Example Deploy&#39;) {<br>      when {<br>        expression { BRANCH_NAME ==~ /(production|staging)/ }<br>           anyOf {<br>              environment name: &#39;DEPLOY_TO&#39;, value: &#39;production&#39;<br>              environment name: &#39;DEPLOY_TO&#39;, value: &#39;staging&#39;<br>                }<br>            }</pre><h3>Parallel</h3><p>Os s<em>tages </em>no <em>Declarative pipeline </em>podem ter uma seção paralela contendo uma lista de <em>stages </em>aninhados a serem executados em paralelo. Observe que um <em>stage </em>deve ter uma e apenas uma das seguintes opções: <strong>stages</strong>, <strong>steps</strong>, <strong>parallel </strong>ou <strong>matrix</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de119f829607a7a4398ddbfab4b208b3/href">https://medium.com/media/de119f829607a7a4398ddbfab4b208b3/href</a></iframe><p>Pronto! Passamos brevemente pelas estruturas mais utilizadas de um pipeline Jenkins. Nos vemos até a próxima publicação.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2afb475660" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criação de uma esteira CI/CD para Python usando o Jenkins]]></title>
            <link>https://matheusvt.medium.com/cria%C3%A7%C3%A3o-de-uma-esteira-ci-cd-para-python-usando-o-jenkins-afe47b9acd22?source=rss-12c072a8631f------2</link>
            <guid isPermaLink="false">https://medium.com/p/afe47b9acd22</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Matheus Villela Torres]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 19:34:25 GMT</pubDate>
            <atom:updated>2020-02-29T00:18:15.631Z</atom:updated>
            <content:encoded><![CDATA[<p>Devido ao grande crescimento da utilização de Python, decidi criar um pipeline de entrega de código para esta linguagem, utilizando somente o Jenkins como orquestrador.</p><p>Repositório do GitHub deste projeto:</p><p><a href="https://github.com/matheusvt2/jenkins-python-full-pipeline">matheusvt2/jenkins-python-full-pipeline</a></p><p><strong>Objetivos:</strong></p><ol><li>Integrar o pipeline com um SCM;</li><li>Construir uma imagem Python usando Dockerfile;</li><li>Realizar testes estáticos;</li><li>Quebrar a entrega caso falhe nos testes (Quality Gate);</li><li>Enviar a imagem para um repositório remoto;</li><li>Ao final do build, executar um container com base na imagem criada.</li></ol><p>O foco desta publicação, não é explicar o arquivo Jenkinsfile criado para a execução deste pipeline e sim testar itens listados acima. <em>Posteriormente publicarei em um outro post com a descrição detalhada do pipeline.</em></p><p>Pós publicação:</p><p><a href="https://medium.com/@matheusvt/explicando-passo-a-passo-um-arquivo-jenkinsfile-e2afb475660">Explicando passo a passo um arquivo Jenkinsfile</a></p><p>Esse pipeline foi criado apenas para conhecimento, notem que não estou realizando testes integrados e também não verifico a integridade da imagem.</p><p><strong>Topologia:</strong></p><ul><li>Servidor Jenkins (<a href="http://192.168.0.11/jenkins">http://192.168.0.11/jenkins</a>)</li><li>Servidor SonarQube (<a href="http://192.168.0.22:9000/">http://192.168.0.22:9000/</a>)</li><li>Servidor de Execução (192.168.0.22)</li></ul><p><strong>Configurações iniciais:</strong></p><p><em>No servidor Jenkins:</em></p><p>Foi necessário a instalação do Docker e do Sonar-Scanner, os links para instalação estão logo abaixo:</p><ul><li><a href="https://docs.docker.com/v17.12/install/">Install Docker</a></li><li><a href="https://docs.sonarqube.org/latest/analysis/scan/sonarscanner/">SonarScanner</a></li><li><a href="https://bitnami.com/stack/jenkins">Jenkins</a></li></ul><p>Obs: importante verificar o caminho onde foi instalado o sonar-scanner.</p><p><em>No servidor SonarQube:</em></p><p>Sem muito o que configurar, no meu caso apenas tive que instalar o Docker e o Docker-Compose. Fica como referência este documento para instalação:</p><p><a href="https://github.com/SonarSource/docker-sonarqube/blob/master/recipes/docker-compose-postgres-example.yml">SonarSource/docker-sonarqube</a></p><p><em>No servidor de Execução:</em></p><p>Como a aplicação é pequena, decidi utilizar o mesmo servidor do SonarQube para a execução, como já tinha o Docker instalado, não precisei de mais nenhuma configuração.</p><p><strong>Parte prática:</strong></p><p>Primeiramente vamos configurar o job no Jenkins. Como o pipeline inteiro foi escrito “as code”, temos apenas que informar ao Jenkins o repositório que vamos buscar as informações, as credenciais de acesso e o nome do arquivo (Jenkinsfile.groovy). <em>Item 1 realizado!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NTCkOInEwBnpaJgt" /><figcaption>Tela de configuração do Job no Jenkins.</figcaption></figure><p>Agora, basta configurar o webhook do SonarQube:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*epkb4dZK8XeAgNOw" /><figcaption>Tela de configuração de Webhook no SonarQube.</figcaption></figure><p>Observe que o endereço padrão é [Endereço do serviço do Jenkins]/sonarqube-webhook.</p><p>Também configurei o SonarQube para aceitar o mínimo de 40% de cobertura do código.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bAgBLP5nlFSN5QEB" /><figcaption>Tela de configuração do Quality Gate no SonarQube.</figcaption></figure><p>Agora sim vamos para a execução do pipeline! Rodei o build manualmente com a opção “Build Now” do Jenkins. <em>É possível configurar um webhook do SCM para o Jenkins para cada push, mas não configurei porque minha instância está rodando em rede privada</em>. O código atendeu os requisitos e passou por todas as etapas com sucesso! <em>Item 2 realizado!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UZOzoUuyHwZp601E" /><figcaption>Tela do Jenkins (Blue Ocean) com o resumo do Pipeline.</figcaption></figure><p>Verificando o status do Quality Gate, percebemos que a resposta enviada pelo webhook do sonar foi: “Quality gate is ‘OK’”. <em>Item 3 realizado!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*obtk1wARRRFmJcq_" /><figcaption>Retorno do step Quality Gate.</figcaption></figure><p>No SonarQube, vemos toda a análise do código:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x0-3d2dQcI2tv-ia" /><figcaption>Tela de resumo do projeto no SonarQube.</figcaption></figure><p>A imagem foi publicada em meu repositório no DockerHub no step “Docker Push”. <em>Item 5 realizado!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*Lcpd020Wz6Phv8bVTSnz8w.png" /><figcaption>Imagem jenkins-python-full-pipeline tag 1 no Docker Hub.</figcaption></figure><p>Finalmente o Jenkins “entrou” via SSH (utilizando o plugin Publish Over SSH) no servidor de execução, fez um pull da imagem que acabamos de criar e rodou o contêiner. <em>Item 6 realizado!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*6geN6axEdQ5-30G7" /></figure><p>Conferindo no servidor de execução, temos tanto a imagem, quanto o contêiner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*hjkSjh-BByzqLUqA" /><figcaption>Imagem criada no pipeline, no servidor de execução.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-3YCVDB2jiySpS-z" /><figcaption>Contêiner executado durante o pipeline.</figcaption></figure><p>Bom, vamos testar se o Quality Gate realmente funciona, voltando na configuração do SonarQube, definimos um nível mínimo de cobertura de 70% e rodamos novamente o build.</p><p>Observe a resposta enviada pelo webhook do sonar foi: “Quality gate is ‘ERROR’”, o pipeline então foi quebrado e não foi feito o push da imagem para o Docker Hub e muito menos foi executado no servidor. <em>Item 4 realizado!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pNwNDMAsK0ximMXn" /></figure><p>Nos vemos até a próxima publicação!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afe47b9acd22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>