<?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 Chi Thuc Nguyen on Medium]]></title>
        <description><![CDATA[Stories by Chi Thuc Nguyen on Medium]]></description>
        <link>https://medium.com/@thucnc?source=rss-2a3d883eaace------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y-XQSNb4DyflrONI4uKRKQ.jpeg</url>
            <title>Stories by Chi Thuc Nguyen on Medium</title>
            <link>https://medium.com/@thucnc?source=rss-2a3d883eaace------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:31:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thucnc/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[Visualize Nginx web Log with GoAccess]]></title>
            <link>https://thucnc.medium.com/visualize-nginx-web-log-with-goaccess-cd80e8771cc4?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd80e8771cc4</guid>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Wed, 17 Feb 2021 11:31:37 GMT</pubDate>
            <atom:updated>2024-04-13T07:26:16.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cqXxIEKdRCvVDngR.png" /></figure><h3>Install GoAccess (Ubuntu 18.04)</h3><h4>Using apt</h4><pre>$ sudo apt install goaccess</pre><p>For the latest version:</p><pre>$ echo &quot;deb http://deb.goaccess.io/ $(lsb_release -cs) main&quot; | sudo tee -a /etc/apt/sources.list.d/goaccess.list<br>$ wget -O - https://deb.goaccess.io/gnugpg.key | sudo apt-key add -<br>$ sudo apt-get update<br>$ sudo apt-get install goaccess</pre><h4>From source</h4><p>Install the dependencies:</p><pre>$ sudo apt-get install libgeoip-dev libncursesw5-dev</pre><p>Download, configure and install goaccess:</p><pre>$ wget https://tar.goaccess.io/goaccess-1.4.tar.gz<br>$ tar -xzvf goaccess-1.4.tar.gz<br>$ cd goaccess-1.4/<br>$ ./configure --enable-utf8 --enable-geoip=legacy<br>$ make<br>$ sudo make install</pre><h3>Determine Log Format</h3><p>Once you have GoAccess installed, you should be ready to start using it. However, first you need to determine the log format of your access log. GoAccess comes with several predefined log format options that you can use. Either you can set them permanently in your <a href="https://goaccess.io/faq#configuration"><strong>configuration file</strong></a> or simply passing it through the <a href="https://goaccess.io/faq#configuration"><strong>command line</strong></a>.</p><h4>Custom log format</h4><p>goaccess config for custom log format: <a href="https://goaccess.io/man#custom-log">https://goaccess.io/man#custom-log</a></p><h3>Run GoAccess</h3><h4>Terminal Output</h4><p>The following prompts a log configuration dialog with predefined log formats for you to choose from and then displays the stats in real-time.</p><pre>goaccess <strong>access.log</strong> -c</pre><h4>Static HTML Output</h4><p>The following parses the access log and displays the stats in a static HTML report.</p><pre>goaccess <strong>access.log</strong> -o report.html --log-format=COMBINED</pre><h4>Real-Time HTML Output</h4><p>The following parses the access log and displays the stats in a real-time HTML report.</p><pre>goaccess <strong>access.log</strong> -o /var/www/html/report.html --log-format=COMBINED --real-time-html</pre><h3>From nginx log format to goaccess</h3><p>Small shell script to convert Nginx log_format to goaccess config can be found here:</p><p><a href="https://github.com/stockrt/nginx2goaccess">stockrt/nginx2goaccess</a></p><p>Usage:</p><pre>$ ./nginx2goaccess.sh &#39;&lt;log_format&gt;&#39;</pre><p>For example:</p><pre>$ ./nginx2goaccess.sh &#39;&quot;$time_local&quot; client=$remote_addr method=$request_method request=&quot;$request&quot; request_length=$request_length status=$status bytes_sent=$bytes_sent body_bytes_sent=$body_bytes_sent referer=$http_referer user_agent=&quot;$http_user_agent&quot; upstream_addr=$upstream_addr upstream_status=$upstream_status request_time=$request_time upstream_response_time=$upstream_response_time upstream_connect_time=$upstream_connect_time upstream_header_time=$upstream_header_time&#39;</pre><p>The output will be something like this:</p><pre>time-format %T<br>date-format %d/%b/%Y<br>log_format &quot;%d:%t %^&quot; client=%h method=%m request=&quot;%r&quot; request_length=%r_length status=%s bytes_sent=%b body_bytes_sent=%b referer=%R user_agent=&quot;%u&quot; upstream_addr=%^ upstream_status=%^ request_time=%T upstream_response_time=%^ upstream_connect_time=%^ upstream_header_time=%^</pre><p>Can be used with -p and read from a config file or placed into ~/.goaccessrc.</p><h3>References</h3><p><a href="https://goaccess.io/">GoAccess - Visual Web Log Analyzer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd80e8771cc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[curl: methods, follow redirects, response headers, response time… and more]]></title>
            <link>https://thucnc.medium.com/curl-methods-follow-redirects-response-headers-response-time-and-more-3dfa93eada37?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dfa93eada37</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[response-time]]></category>
            <category><![CDATA[response-header]]></category>
            <category><![CDATA[post]]></category>
            <category><![CDATA[curl]]></category>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Wed, 06 Jan 2021 07:35:57 GMT</pubDate>
            <atom:updated>2021-01-06T08:01:44.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>curl: methods, follow redirects, response headers, response time, multipart upload, authentication… and more</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nlLiffj5UHDYyZ-_.png" /></figure><h3>Basic usage: simple GET method</h3><p>This will make a GET request to the given URL and print response to stdout.</p><pre>$ curl <a href="https://example.com/">https://example.com</a></pre><h3>Ignore invalid and self-signed SSL connection errors with curl</h3><p>Use -k or --insecure option</p><pre>$ curl -k https://domain-with-insecure-ssl.com</pre><h3>Print response headers</h3><p>Use -i option to print response headers and the response itself, -I option to omit the response and print response headers only.</p><pre>$ curl -I <a href="https://example.com/">https://example.com</a></pre><p>Sample response:</p><pre>HTTP/2 200<br>accept-ranges: bytes<br>age: 135602<br>cache-control: max-age=604800<br>content-type: text/html; charset=UTF-8<br>date: Wed, 06 Jan 2021 07:16:58 GMT<br>etag: &quot;3147526947&quot;<br>expires: Wed, 13 Jan 2021 07:16:58 GMT<br>last-modified: Thu, 17 Oct 2019 07:18:26 GMT<br>server: ECS (oxr/8310)<br>x-cache: HIT<br>content-length: 1256</pre><h3>Print payload size and response time</h3><p>For this, we need a custom output template. First, create a template file, curl-format.txt for example, with following content:</p><pre>        size_request:  %{size_request} bytes\n<br>         size_upload:  %{size_upload} bytes\n<br>       size_download:  %{size_download} bytes\n<br>         size_header:  %{size_header} bytes\n</pre><pre>     time_namelookup:  %{time_namelookup}s\n<br>        time_connect:  %{time_connect}s\n<br>     time_appconnect:  %{time_appconnect}s\n<br>    time_pretransfer:  %{time_pretransfer}s\n<br>       time_redirect:  %{time_redirect}s\n<br>  time_starttransfer:  %{time_starttransfer}s\n<br>                     ----------\n<br>          time_total:  %{time_total}s\n</pre><p>Then using -w option to specify output format, as following:</p><pre>$ curl -w &quot;<a href="http://twitter.com/curl">@curl</a>-format.txt&quot; example.com</pre><p>Sample output:</p><pre>        size_request:  76 bytes<br>         size_upload:  0 bytes<br>       size_download:  0 bytes<br>         size_header:  351 bytes<br>     time_namelookup:  0.001756s<br>        time_connect:  0.236285s<br>     time_appconnect:  0.000000s<br>    time_pretransfer:  0.236358s<br>       time_redirect:  0.000000s<br>  time_starttransfer:  0.478430s<br>                     ----------<br>          time_total:  0.478695s</pre><h3>Follow redirects</h3><p>It’s extremely common for HTTP servers to return a 301 or 302 redirect for a given URL. One common example of this is to redirect your browser from an HTTP URL to HTTPS, like <a href="http://ucode.vn/">http://ucode.vn</a> to <a href="http://ucode.vn/">https://ucode.vn</a>.</p><pre>$ curl -i ucode.vn</pre><p>And we can see <strong>HTTP/1.1 301 Moved Permanently </strong>code:</p><pre><strong>HTTP/1.1 301 Moved Permanently</strong><br>Server: nginx/1.18.0 (Ubuntu)<br>Date: Wed, 06 Jan 2021 07:31:13 GMT<br>Content-Type: text/html<br>Content-Length: 178<br>Connection: keep-alive<br><strong>Location: </strong><a href="https://ucode.vn/"><strong>https://ucode.vn/</strong></a></pre><pre>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;301 Moved Permanently&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;center&gt;&lt;h1&gt;301 Moved Permanently&lt;/h1&gt;&lt;/center&gt;<br>&lt;hr&gt;&lt;center&gt;nginx/1.18.0 (Ubuntu)&lt;/center&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Running curl command with -L or --location options will automatically handle any 3XX redirects and will retrieve whatever data is returned by the resulting URL.</p><pre>$ curl -I -L ucode.vn</pre><p>and we can see:</p><pre>HTTP/1.1 301 Moved Permanently<br>Server: nginx/1.18.0 (Ubuntu)<br>Date: Wed, 06 Jan 2021 07:33:53 GMT<br>Content-Type: text/html<br>Content-Length: 178<br>Connection: keep-alive<br><strong>Location: </strong><a href="https://ucode.vn/"><strong>https://ucode.vn/</strong></a></pre><pre>HTTP/1.1 200 OK<br>Server: nginx/1.18.0 (Ubuntu)<br>Date: Wed, 06 Jan 2021 07:33:53 GMT<br>Content-Type: text/html; charset=utf-8<br>Content-Length: 85913<br>Connection: keep-alive<br>X-Powered-By: Express<br>Set-Cookie: UCODE_LOCALE=vi; Path=/; Expires=Thu, 06 Jan 2022 07:33:53 GMT; SameSite=Lax<br>Set-Cookie: UCODE_PRODUCTION_IDE_CONFIGS=%7B%22theme%22%3A%22dark%22%2C%22layout%22%3A%22vertical%22%2C%22language%22%3A%7B%22id%22%3A%22python%22%2C%22name%22%3A%22Python%20(Interactive)%22%7D%7D; Path=/<br>Set-Cookie: UCODE_LOCALE=vi; Max-Age=2592000; Path=/<br>ETag: &quot;14f99-LowxBo/SA1VGY9E29rvOz4t6Zck&quot;<br>Accept-Ranges: none<br>Vary: Accept-Encoding</pre><h3>Making a POST request</h3><p>Useful options:</p><ul><li>Request method: -X POST</li><li>Content-type header: -H &quot;Content-Type: application/x-www-form-urlencoded&quot; (default) or -H &quot;Content-Type: application/json&quot;</li><li>Form url-encoded data: -d &quot;param1=value1&amp;param2=value2&quot; or -d <a href="http://twitter.com/data">@data</a>.txt</li><li>Json data: -d &#39;{&quot;key1&quot;:&quot;value1&quot;, &quot;key2&quot;:&quot;value2&quot;}’ or -d <a href="http://twitter.com/data">@data</a>.json</li></ul><h4>Examples:</h4><p><strong>POST application/x-www-form-urlencoded:</strong></p><pre>$ curl -d &quot;param1=value1&amp;param2=value2&quot; -X POST {url}</pre><p>or with a data file:</p><pre>$ curl -d &quot;@<strong>data.txt</strong>&quot; -X POST {url}</pre><p>sample content of data.txt:</p><pre>param1=value1&amp;param2=value2</pre><p><strong>POST application/json:</strong></p><pre>$ curl -d &#39;{&quot;key1&quot;:&quot;value1&quot;, &quot;key2&quot;:&quot;value2&quot;}&#39; -H &quot;Content-Type: application/json&quot; -X POST {url}</pre><p>or with a data file:</p><pre>$ curl -d &quot;@<strong>data.json</strong>&quot; -X POST {url}</pre><p>sample content of data.json file:</p><pre>{<br>    &quot;key1&quot;:&quot;value1&quot;,  <br>    &quot;key2&quot;:&quot;value2&quot;<br>}</pre><h3>HTTP Basic authentication</h3><pre>$ curl <a href="http://username:passwd@domain.com/">http://<strong>username:passwd</strong>@domain.com</a></pre><p>or using -u option:</p><pre>$ curl -u username:passwd {url}</pre><h3>Multipart file upload</h3><p>Using -F or --form option:</p><pre>$ curl -F <strong>upload</strong>=@localfilename -F <strong>press</strong>=<strong>OK </strong>[URL]</pre><p>The corresponding HTML form could be written like this:</p><pre>&lt;form method=&quot;POST&quot; enctype=&#39;<strong>multipart/form-data</strong>&#39; action=&quot;upload.php&quot;&gt;<br>  &lt;input type=file name=<strong>upload</strong>&gt;<br>  &lt;input type=submit name=<strong>press </strong>value=&quot;<strong>OK</strong>&quot;&gt;<br>&lt;/form&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dfa93eada37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Nginx to proxy your S3 files]]></title>
            <link>https://thucnc.medium.com/how-to-use-nginx-to-proxy-your-s3-files-760acc869e8?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/760acc869e8</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[proxy-cache]]></category>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Sun, 18 Oct 2020 03:19:28 GMT</pubDate>
            <atom:updated>2020-10-18T03:19:28.535Z</atom:updated>
            <content:encoded><![CDATA[<p>There are many benefits you can get when using Nginx to proxy your S3 (and others) files, such as:</p><ul><li>Proxy cache to leverage browser caching</li><li>URLs masking that helps a lot in case you change cloud provider later</li><li>Speed up transferring by offload SSL/TLS</li><li>…</li></ul><p>This tutorial helps you through detailed steps you can follow to configure Nginx to proxy your files in S3, and leverage browser caching.</p><h3>Inspect AWS S3 response headers</h3><p>First, let inspect AWS S3 files’ response headers:</p><pre>$ curl -I <a href="https://ucodevn.s3-ap-southeast-1.amazonaws.com/image_restored/1867/courses/42/17773/id365442.png">https://ucodevn.s3-ap-southeast-1.amazonaws.com/image_restored/1867/courses/42/17773/id365442.png</a></pre><p>You will get a result similar to this:</p><pre>HTTP/1.1 200 OK<br>x-amz-id-2: C8uQhUZqP8hZ3hACa3fFbG6l29kXYq/VS+i5otl9DNRHAHM4wnM+28Yk4LzDt9L/Q8OuMbLGeX4=<br>x-amz-request-id: 4A0191D9383DE48B<br>Date: Sun, 18 Oct 2020 01:47:31 GMT<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;<strong>356b5d3ba55b3f00bd30b071e298c5fe</strong>&quot;<br>Accept-Ranges: bytes<br>Content-Type: image/png<br>Content-Length: 7481<br>Server: AmazonS3</pre><p>We can see missing Cache-Control but Conditional GET headers have already been configured. When we reuse E-Tag/Last-Modified (that’s how a browser’s client-side cache works), we get HTTP 304 alongside with empty Content-Length. An interpretation of that is the client (curl in our case) queries the resource saying that no data transfer required unless the file has been modified on the server:</p><pre>$ curl -I  <a href="https://ucodevn.s3-ap-southeast-1.amazonaws.com/image_restored/1867/courses/42/17773/id365442.png">https://ucodevn.s3-ap-southeast-1.amazonaws.com/image_restored/1867/courses/42/17773/id365442.png</a> --header &quot;<strong>If-None-Match</strong>: <strong>356b5d3ba55b3f00bd30b071e298c5fe</strong>&quot;</pre><p>And we will get HTTP 304 Not Modified<strong> </strong>with no data re-send:</p><pre>HTTP/1.1 <strong>304 Not Modified</strong><br>x-amz-id-2: 3HoshGpkZODJGCObVCv37r95mX2JI01A/CI9S7Kqj8uquI8GuNELi+a/1D0G7Sfu/GsTfiulT1U=<br>x-amz-request-id: 9C4B0A7CFF6107BB<br>Date: Sun, 18 Oct 2020 01:49:22 GMT<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;356b5d3ba55b3f00bd30b071e298c5fe&quot;<br><strong>Server</strong>: <strong>AmazonS3</strong></pre><p>Or using If-Modified-Since header:</p><pre>$ curl -I  <a href="https://ucodevn.s3-ap-southeast-1.amazonaws.com/image_restored/1867/courses/42/17773/id365442.png">https://ucodevn.s3-ap-southeast-1.amazonaws.com/image_restored/1867/courses/42/17773/id365442.png</a> --header &quot;<strong>If-Modified-Since</strong>: <strong>Mon, 27 Jul 2020 07:48:22 GMT</strong>&quot;</pre><p>Similar result:</p><pre>HTTP/1.1 <strong>304 Not Modified</strong><br>x-amz-id-2: 2JuMRfdvkgnL8O5J07H4H5J4U7D7h7KOMHfzkDuqGiUIREduB39gFc6fIxgWm+419M564IsR2pY=<br>x-amz-request-id: 80E743CCBC58B5DC<br>Date: Sun, 18 Oct 2020 01:51:45 GMT<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;356b5d3ba55b3f00bd30b071e298c5fe&quot;<br><strong>Server</strong>: <strong>AmazonS3</strong><br>Connection: close</pre><h3>Proxy using Nginx</h3><p>Use the configuration below to proxy your S3 files with Nginx as following. Please note that there is no slash (/) at the end of proxy_pass URL.</p><pre>server {<br>  listen 80;<br>  listen 443 ssl;<br>  server_name  statics.yourside.com;<br>  access_log  /var/log/nginx/statics.access.log  combined;<br>  error_log   /var/log/nginx/statics.error.log;<br>  <strong>set $bucket &quot;ucodevn.s3-ap-southeast-1.amazonaws.com&quot;;</strong><br>  sendfile on;</pre><pre>location <strong>/</strong> {<br>    <strong>resolver </strong>8.8.8.8;<br>    proxy_http_version     1.1;<br>    proxy_redirect off;<br>    proxy_set_header       Connection &quot;&quot;;<br>    proxy_set_header       Authorization &#39;&#39;;<br>    proxy_set_header       Host $bucket;<br>    proxy_set_header       X-Real-IP $remote_addr;<br>    proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_hide_header      x-amz-id-2;<br>    proxy_hide_header      x-amz-request-id;<br>    proxy_hide_header      x-amz-meta-server-side-encryption;<br>    proxy_hide_header      x-amz-server-side-encryption;<br>    proxy_hide_header      Set-Cookie;<br>    proxy_ignore_headers   Set-Cookie;<br>    proxy_intercept_errors on;<br>    add_header             Cache-Control max-age=31536000;<br>    <strong>proxy_pass             </strong><a href="https://$bucket/"><strong>https://$bucket</strong></a><strong>; # without trailing slash</strong><br>  }<br>}</pre><p>Restart Nginx:</p><pre>$ sudo nginx -t<br>$ sudo service nginx restart</pre><p>And try to access your file via your own URL (use -k in case you don’t have an SSL certificate yet):</p><pre>$ curl -I -k https://<strong>statics.yourside.com</strong>/{path_to_your_file}</pre><p>For instances:</p><pre>$ curl -I -k <a href="https://cdn.ucode.vn/image_restored/1867/courses/42/17773/id365442.png">https://cdn.ucode.vn/image_restored/1867/courses/42/17773/id365442.png</a></pre><p>And you will see Cache-Control header as following. Note that the Server is nginx now, but not AmazonS3 anymore.</p><pre>HTTP/1.1 200 OK<br><strong>Server</strong>: <strong>nginx/1.18.0 (Ubuntu)</strong><br>Date: Sun, 18 Oct 2020 02:11:57 GMT<br>Content-Type: image/png<br>Content-Length: 7481<br>Connection: keep-alive<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;356b5d3ba55b3f00bd30b071e298c5fe&quot;<br>Accept-Ranges: bytes<br><strong>Cache-Control</strong>: max-age=31536000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*nroSt62KDreLxWOE.png" /><figcaption>Nginx proxy without cache</figcaption></figure><p>Now, we can try request the file using Nginx proxy with Conditional GET:</p><pre>$ curl -I -k <a href="https://cdn.ucode.vn/image_restored/1867/courses/42/17773/id365442.png">https://cdn.ucode.vn/image_restored/1867/courses/42/17773/id365442.png</a> --header &quot;If-None-Match: 356b5d3ba55b3f00bd30b071e298c5fe&quot;</pre><p>And the same HTTP 304 status as responded from AmazonS3, but the file was served vid Nginx server also:</p><pre>HTTP/1.1 <strong>304 Not Modified</strong><br><strong>Server</strong>: <strong>nginx/1.18.0 (Ubuntu)</strong><br>Date: Sun, 18 Oct 2020 02:24:46 GMT<br>Connection: keep-alive<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;356b5d3ba55b3f00bd30b071e298c5fe&quot;<br>Cache-Control: max-age=31536000</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*qZr7XqBdUsJ2LFF6.png" /><figcaption>Proxy request with Condition GET</figcaption></figure><h3>Proxy using Nginx with proxy cache</h3><p>Add another sub-path to serve file via proxy cache. We will add an additional <strong>X-Cache-Status</strong> header, its value is MISS until cache warmed up after first request.</p><p>Nginx configuration:</p><pre><strong>proxy_cache_path</strong>   /tmp/ levels=1:2 keys_zone=<strong>s3_cache</strong>:10m max_size=500m inactive=60m use_temp_path=off;</pre><pre>server {<br>  listen 80;<br>  listen 443 ssl;<br>  server_name  cdn.ucode.vn;<br>  access_log   /var/log/nginx/ucode-cdn.access.log  combined;<br>  error_log   /var/log/nginx/ucode-cdn.error.log;<br>  set $bucket &quot;ucodevn.s3-ap-southeast-1.amazonaws.com&quot;;<br>  sendfile        on;</pre><pre># This configuration uses a 60 minute cache for files requested:<br>  location <strong>^~ /cached/</strong> {<br>    rewrite           <strong>/cached(.*) $1 break;</strong><br>    resolver 8.8.8.8;<br>    <strong>proxy_cache            s3_cache;</strong><br>    proxy_http_version     1.1;<br>    proxy_redirect off;<br>    proxy_set_header       Connection &quot;&quot;;<br>    proxy_set_header       Authorization &#39;&#39;;<br>    proxy_set_header       Host $bucket;<br>    proxy_set_header       X-Real-IP $remote_addr;<br>    proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_hide_header      x-amz-id-2;<br>    proxy_hide_header      x-amz-request-id;<br>    proxy_hide_header      x-amz-meta-server-side-encryption;<br>    proxy_hide_header      x-amz-server-side-encryption;<br>    proxy_hide_header      Set-Cookie;<br>    proxy_ignore_headers   Set-Cookie;<br>    <strong>proxy_cache_revalidate on;<br></strong>    proxy_intercept_errors on;<br>    proxy_cache_use_stale  error timeout updating http_500 http_502 http_503 http_504;<br>    proxy_cache_lock       on;<br>    proxy_cache_valid      200 304 60m;<br>    add_header             Cache-Control max-age=31536000;<br>    add_header             <strong>X-Cache-Status $upstream_cache_status;</strong><br>    proxy_pass             <a href="https://$bucket/">https://$bucket</a>; # without trailing slash<br>  }</pre><pre># This configuration provides direct access to the Object Storage bucket:<br>  location / {<br>    resolver 8.8.8.8;<br>    proxy_http_version     1.1;<br>    proxy_redirect off;<br>    proxy_set_header       Connection &quot;&quot;;<br>    proxy_set_header       Authorization &#39;&#39;;<br>    proxy_set_header       Host $bucket;<br>    proxy_set_header       X-Real-IP $remote_addr;<br>    proxy_set_header       X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_hide_header      x-amz-id-2;<br>    proxy_hide_header      x-amz-request-id;<br>    proxy_hide_header      x-amz-meta-server-side-encryption;<br>    proxy_hide_header      x-amz-server-side-encryption;<br>    proxy_hide_header      Set-Cookie;<br>    proxy_ignore_headers   Set-Cookie;<br>    proxy_intercept_errors on;<br>    add_header             Cache-Control max-age=31536000;<br>    proxy_pass             <a href="https://$bucket/">https://$bucket</a>;<br>  }<br>}</pre><p>At first request, the <strong>X-Cache-Status </strong>should be MISS:</p><pre>$ curl -I -k <a href="https://cdn.ucode.vn/cached/image_restored/1867/courses/42/17773/">https://cdn.ucode.vn/cached/image_restored/1867/courses/42/17773/</a><br>id365442.png --header &quot;If-None-Match: 356b5d3ba55b3f00bd30b071e298c5fe&quot;</pre><p>After that, a new cached file will be created somewhere inside /tmp/ folder as configured above.</p><pre>HTTP/1.1 200 OK<br>Server: nginx/1.18.0 (Ubuntu)<br>Date: Sun, 18 Oct 2020 03:11:17 GMT<br>Content-Type: image/png<br>Content-Length: 7481<br>Connection: keep-alive<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;356b5d3ba55b3f00bd30b071e298c5fe&quot;<br>Cache-Control: max-age=31536000<br>X-Cache-Status: <strong>MISS</strong><br>Accept-Ranges: bytes</pre><p>Then the cache will be warmed up after first request, following requests will be served directly from our Nginx without re-fetch from the origin (AmazonS3):</p><pre>$ curl -I -k <a href="https://cdn.ucode.vn/cached/image_restored/1867/courses/42/17773/">https://cdn.ucode.vn/cached/image_restored/1867/courses/42/17773/</a><br>id365442.png --header &quot;If-None-Match: 356b5d3ba55b3f00bd30b071e298c5fe&quot;</pre><p>The headers now will be like this (with much shorter response time):</p><pre>HTTP/1.1 200 OK<br>Server: nginx/1.18.0 (Ubuntu)<br>Date: Sun, 18 Oct 2020 03:14:19 GMT<br>Content-Type: image/png<br>Content-Length: 7481<br>Connection: keep-alive<br>Last-Modified: Mon, 27 Jul 2020 07:48:22 GMT<br>ETag: &quot;356b5d3ba55b3f00bd30b071e298c5fe&quot;<br>Cache-Control: max-age=31536000<br><strong>X-Cache-Status:</strong> <strong>HIT</strong><br>Accept-Ranges: bytes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*anTXiq4gtdaaxJtc.png" /><figcaption>Proxy cache HIT</figcaption></figure><p>Some optimized settings used above are based on <a href="https://www.nginx.com/blog/nginx-caching-guide/">Nginx official documentation</a> I provide the Nginx S3 configuration with optimized caching settings that supports the following options:</p><ul><li><strong>proxy_cache_revalidate</strong> instructs NGINX to use conditional GET requests when refreshing content from the origin servers</li><li>the updating parameter to the <strong>proxy_cache_use_stale</strong> directive instructs NGINX to deliver stale content when clients request an item while an update to it is being downloaded from the origin server, instead of forwarding repeated requests to the server</li><li>with <strong>proxy_cache_lock</strong> enabled, if multiple clients request a file that is not currently in the cache (a MISS), only the first of those requests is allowed through to the origin server.</li></ul><p>Happy Ops-ing!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=760acc869e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Docker & Containers tutorial]]></title>
            <link>https://thucnc.medium.com/a-docker-containers-tutorial-a6d6184a5617?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6d6184a5617</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Tue, 25 Aug 2020 10:32:16 GMT</pubDate>
            <atom:updated>2020-11-12T02:51:22.506Z</atom:updated>
            <content:encoded><![CDATA[<h3>Installing Docker</h3><h4>Ubuntu</h4><p>From official docs: <a href="https://docs.docker.com/engine/install/ubuntu/">https://docs.docker.com/engine/install/ubuntu/</a></p><p>Uninstalling old versions:</p><pre>sudo apt-get remove docker docker-engine docker.io containerd runc</pre><p><strong>Set up the respository</strong></p><pre>sudo apt update</pre><p>Install packages to allow apt to use a repository over HTTPS:</p><pre>sudo apt-get install \<br>    apt-transport-https \<br>    ca-certificates \<br>    curl \<br>    gnupg-agent \<br>    software-properties-common</pre><p>Add Docker’s official GPG key:</p><pre>curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -</pre><p>Add Docker repository:</p><pre>sudo add-apt-repository \<br>   &quot;deb [arch=amd64] https://download.docker.com/linux/ubuntu \<br>   $(lsb_release -cs) \<br>   stable&quot;</pre><p><strong>Install Docker CE</strong></p><pre>$ sudo apt update<br>$ sudo apt-get install docker-ce docker-ce-cli containerd.io</pre><p>Verify that Docker CE is installed correctly by running the hello-world image:</p><pre>$ sudo docker run hello-world<br>$ sudo docker images</pre><h4>Manage Docker as a non-root user</h4><p>The docker daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user root and other users can only access it using sudo. The docker daemon always runs as the root user.</p><p>If you don’t want to use sudo when you use the docker command, create a Unix group called docker and add users to it. When the docker daemon starts, it makes the ownership of the Unix socket read/writable by the docker group.</p><p>To create the docker group and add your user:</p><ol><li>Create the docker group and add your user to the docker group:</li></ol><pre>sudo groupadd docker<br>sudo usermod -aG docker $USER</pre><p>2. Log out and log back in so that your group membership is re-evaluated.</p><h3>Deploying Your First Docker Container</h3><h4>Running A Container</h4><p>You can find existing images at <a href="https://store.docker.com/">https://store.docker.com/</a> or by using the command docker search &lt;name&gt;. For example, to find an image for <em>Redis</em>, you would use:</p><pre>docker search redis</pre><p>The Docker CLI has a command called <em>run</em> which will start a container based on a Docker Image. The structure is <em>docker run &lt;options&gt; &lt;image-name&gt;/.</em></p><p>To run the <em>latest</em> (default) release of Redis image as a background service:</p><pre>docker run -d redis</pre><p>If a particular version was required, it could be specified as a tag, for example, version 3.2 would be <em>docker run -d redis:3.2</em>.</p><p><strong>Note:</strong> without option -d, the container will start then stop immediately after finishing specific command. For example: docker run alpine ls /</p><h4>Finding Running Containers</h4><p>Lists all running containers, the image used to start the container and uptime:</p><pre>docker ps</pre><p>Sample out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2Xta5kt4nA2rjIRv5bv3g.png" /></figure><p>Get more details about a running container:</p><pre>docker inspect &lt;friendly-name|container-id&gt;</pre><p>Display messages the container has written to standard error or standard out:</p><pre>docker logs &lt;friendly-name|container-id&gt;</pre><h4>Accessing Redis</h4><p>The reason is that each container is sandboxed. If a service needs to be accessible by a process not running in a container, then the port needs to be exposed via the Host. Ports are bound when containers are started using <em>-p &lt;host-port&gt;:&lt;container-port&gt;</em> option:</p><pre>docker run -d --name redisHostPort -p 6379:6379 redis:latest</pre><p>By default, the port on the host is mapped to 0.0.0.0, which means all IP addresses. You can specify a particular IP address when you define the port mapping, for example, <em>-p 127.0.0.1:6379:6379</em></p><p>The option <em>-p 6379</em> exposes <em>Redis</em> but on a randomly available port. This will allow us to run multiple instances of Redis container at the same time:</p><pre>docker run -d --name redisDynamic -p 6379 redis:latest</pre><p>To discover that random port, use this command: docker port redisDynamic 6379 or use familiar docker ps command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5uuLgUEyZCTPySKSr9AKg.png" /></figure><h4>Persisting Data</h4><p>Containers are designed to be stateless, in the way that that the data stored keeps being removed when you delete and re-create a container. Binding directories (also known as volumes) with option <em>-v &lt;host-dir&gt;:&lt;container-dir&gt; </em>allow data to be persisted on the host. This allows you to upgrade or change containers without losing your data.</p><pre>docker run -d --name redisMapped \<br>-v /opt/docker/data/redis:/data redis</pre><pre>docker ps -a</pre><h4>Getting access to a bash shell inside of a container</h4><p>To exec a command inside the container:</p><pre>docker exec {container-id} {command}</pre><p>To interact with the container (for example, to access a bash shell) you could include the options <em>-it:</em></p><pre>docker exec -it {container-id} sh</pre><p>or:</p><pre>docker exec -it {container-id} /bin/bash</pre><h4>Get help form CLI</h4><pre>docker --help<br>docker {command} --help</pre><h4>Useful commands</h4><p>List containers:</p><pre>docker ps -a</pre><p>Stop using container id</p><pre>docker stop &lt;id&gt;</pre><p>Remove a container</p><pre>docker rm &lt;id&gt;</pre><p>List images</p><pre>docker images</pre><p>Remove an image</p><pre>docker image rm &lt;image_name:tag or id&gt;</pre><h3>Building your own Container Images</h3><h4>Create Dockerfile</h4><p>Docker Images start from a base image. The base image should include the platform dependencies required by your application, for example, having the JVM or CLR installed.</p><p>This base image is defined as an instruction in the Dockerfile. Docker Images are built based on the contents of a Dockerfile. The Dockerfile is a list of instructions describing how to deploy your application.</p><p>In this example, our base image is the Alpine version of Nginx. This provides the configured web server on the Linux Alpine distribution.</p><p>Create your Dockerfile for building your image by copying the contents below into the editor:</p><pre>FROM nginx:alpine<br>COPY . /usr/share/nginx/html</pre><p>You should have an index.html file as well:</p><pre>&lt;h1&gt;Hello World&lt;/h1&gt;</pre><h4>Build Docker Image</h4><p>The Dockerfile is used by the Docker CLI <em>build</em> command. The <em>build</em> command executes each instruction within the Dockerfile. The result is a built Docker Image that can be launched and run your configured app.</p><p>The format is <em>docker build -t &lt;build-directory&gt;</em>. The <em>-t</em> parameter allows you to specify a friendly name for the image and a tag, commonly used as a version number.</p><pre>docker build -t webserver-image:v1 .</pre><p>Then you can view a list of all the images on the host using:</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Biuh0P-_w-OOBeI8U-AGQA.png" /></figure><h4>Launch the image</h4><p>Launch our newly built image providing the friendly name and tag. As it’s a web server, bind port 80 to our host using the <em>-p</em> parameter.</p><pre>docker run -d -p 80:80 --name webapp webserver-image:v1</pre><p>Once started, you’ll be able to access the results of port 80 via curl docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2J3j9az1mYdx4SeVtZbVA.png" /></figure><h3>Container Orchestration using Docker Compose</h3><p>When working with multiple containers, it can be difficult to manage the starting along with the configuration of variables and links. To solve this problem, Docker has a tool called Docker Compose to manage the orchestration, of launching, of containers.</p><h4>Installing Docker Compose</h4><p>Official docs: <a href="https://docs.docker.com/compose/install/">https://docs.docker.com/compose/install/</a></p><p>To install Docker Compose, just download latest version (found on the link above) and apply executable permission to the binary:</p><pre>sudo curl -L &quot;<a href="https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname">https://github.com/docker/compose/releases/download/1.27.4/docker-compose-$(uname</a> -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose</pre><pre>sudo chmod +x /usr/local/bin/docker-compose</pre><pre>docker-compose --version</pre><h4>Official tutorial</h4><p><a href="https://docs.docker.com/compose/gettingstarted/"></a></p><p>Another tutorial:</p><p><a href="https://www.educative.io/blog/docker-compose-tutorial">Docker Compose Tutorial: advanced Docker made simple</a></p><h4>Docker compose file</h4><p>Docker Compose files work by applying mutiple commands that are declared within a single docker-compose.yml configuration file. The basic structure of a Docker Compose YAML file looks like this:</p><pre>version: &#39;X&#39;</pre><pre>services:<br>  web:<br>    build: .<br>    ports:<br>     - &quot;5000:5000&quot;<br>    volumes:<br>     - .:/code<br>  redis:<br>    image: redis</pre><p>Example:</p><pre>version: &#39;3&#39;<br>services:<br>  web:<br>    # Path to Dockerfile.<br>    # &#39;.&#39; represents the current directory in which<br>    # docker-compose.yml is present.<br>    build: .</pre><pre>    # Mapping of container port to host<br>    <br>    ports:<br>      - &quot;5000:5000&quot;<br>    # Mount volume <br>    volumes:<br>      - &quot;/usercode/:/code&quot;</pre><pre>    # Link database container to app container for reachability.<br>    links:<br>      - &quot;database:backenddb&quot;<br>    <br>  database:</pre><pre>    # image to fetch from docker hub<br>    image: mysql/mysql-server:5.7</pre><pre>    # Environment variables for startup script<br>    # container will use these variables<br>    # to start the container with these define variables. <br>    environment:<br>      - &quot;MYSQL_ROOT_PASSWORD=root&quot;<br>      - &quot;MYSQL_USER=testuser&quot;<br>      - &quot;MYSQL_PASSWORD=admin123&quot;<br>      - &quot;MYSQL_DATABASE=backend&quot;<br>    # Mount init.sql file to automatically run <br>    # and create tables for us.<br>    # everything in docker-entrypoint-initdb.d folder<br>    # is executed as soon as container is up nd running.<br>    volumes:<br>      - &quot;/usercode/db/init.sql:/docker-entrypoint-initdb.d/init.sql&quot;</pre><h4>Useful commands</h4><p>These commands should be run inside a folder with docker-compose.yml.</p><p>Builds images in the docker-compose.yml file:</p><pre>docker-compose build</pre><p>Create and start containers:</p><pre>docker-compose up</pre><p>Start and run containers in background (detach mode):</p><pre>docker-compose up -d</pre><p>Stops the running containers of specified services:</p><pre>docker-compose stop</pre><p>List all the containers in the current docker-compose file:</p><pre>docker-compose ps</pre><p>Remove containers, networks and images (for services defined in the compose file):</p><pre>docker-compose down</pre><p>Scale with multiple instances of a service:</p><pre>docker-compose up -d --scale SERVICE=NUM</pre><p>for example:</p><pre>docker-compose up -d --scale workers=5</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6d6184a5617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to secure your Nginx website with SSL using Let’s Encrypt on Ubuntu 18.04]]></title>
            <link>https://thucnc.medium.com/how-to-secure-your-nginx-website-with-ssl-using-lets-encrypt-on-ubuntu-18-04-e7a77517798f?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a77517798f</guid>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Mon, 18 May 2020 10:18:15 GMT</pubDate>
            <atom:updated>2020-05-18T10:18:15.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iJEjjaQn3qLrVAdg.jpg" /></figure><p>Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates for enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, <strong>Certbot</strong>, that attempts to automate most of the required steps for both Apache and Nginx.</p><h3>Install certbot</h3><pre>sudo add-apt-repository ppa:certbot/certbot<br>sudo apt update<br>sudo apt-get install certbot<br>sudo apt-get install python-certbot-nginx<br>certbot --version</pre><h3>Obtain an SSL certificate</h3><p>You should already a website configuration for your domain in nginx at /etc/nginx/sites-available/<strong>example.com</strong>:</p><pre>server {<br>  ...<br>  server_name <strong>example.com www.example.com</strong>;<br>  ...<br>}</pre><p>Then obtain an SSL certificate and get certbort do all the configuration by itself for Nginx:</p><pre>$ sudo certbot --nginx -d <strong>example.com </strong>-d <strong>www.example.com</strong></pre><p>You can choose to auto redirect HTTP request to HTTPS during this command execution.</p><p>You can double check your nginx website configuration after this command /etc/nginx/sites-available/<strong>example.com</strong>:</p><pre>server {<br>    server_name <strong>example.com</strong>; <br>    ...<br>    listen 443 ssl; # managed by Certbot<br>    ssl_certificate /etc/letsencrypt/live/<strong>example.com</strong>/fullchain.pem; <br>    ssl_certificate_key /etc/letsencrypt/live/<strong>example.com</strong>/privkey.pem;<br>    include /etc/letsencrypt/options-ssl-nginx.conf;<br>    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; <br>}</pre><pre>server {<br>    if ($host = hr.teko.vn) {<br>        return 301 <a href="https://$host$request_uri/">https://$host$request_uri</a>;<br>    } # managed by Certbot</pre><pre>    listen 80;<br>    server_name <strong>example.com</strong>;<br>    return 404; # managed by Certbot</pre><pre>}</pre><p>Then restart your nginx and enjoy your secured HTTPS website:</p><pre>$ sudo nginx -t<br>$ sudo service nginx reload</pre><h3>Auto renew Let’s Encrypt’s certificate</h3><p>Let’s Encrypt’s certificates are only valid for ninety days. This is to encourage users to automate their certificate renewal process. The certbot package we installed takes care of this for us by adding a renew script to /etc/cron.d. This script runs twice a day and will automatically renew any certificate that’s within thirty days of expiration.</p><p>You can see this cronjob in /etc/cron.d/certbot file:</p><pre>0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system &amp;&amp; perl -e &#39;sleep int(rand(43200))&#39; &amp;&amp; certbot -q renew</pre><p>To test the renewal process, you can do a dry run with certbot:</p><pre>sudo certbot renew - dry-run</pre><p>If you see no errors, you’re all set. Enjoy your secured website!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a77517798f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to config NGINX logging for Application Performance Monitoring]]></title>
            <link>https://thucnc.medium.com/how-to-config-nginx-logging-for-application-performance-monitoring-dc927325985?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc927325985</guid>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Mon, 18 May 2020 04:01:33 GMT</pubDate>
            <atom:updated>2020-05-18T08:00:13.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FNK2URm_YdjGFpIN.png" /></figure><h4>NGINX Built‑In Timing Variables</h4><p>NGINX provides a number of built‑in timing variables that you can include in log entries. All are measured in seconds with millisecond resolution.</p><ul><li><a href="https://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_time">$request_time</a> – Full request time, starting when NGINX reads the first byte from the client and ending when NGINX sends the last byte of the response body</li><li><a href="https://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_connect_time">$upstream_connect_time</a> – Time spent establishing a connection with an upstream server</li><li><a href="https://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time">$upstream_header_time</a> – Time between establishing a connection to an upstream server and receiving the first byte of the response header</li><li><a href="https://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time">$upstream_response_time</a> – Time between establishing a connection to an upstream server and receiving the last byte of the response body</li></ul><p>Define log format in nginx.conf file (Ubuntu 18.04 used as example here)</p><pre>$ sudo vim /etc/nginx/nginx.conf</pre><p>And add a log format in http section:</p><pre>http {<br>  ...<br>  ##<br>  # Logging Settings<br>  ##<br>  log_format <strong>apm</strong> &#39;&quot;$time_local&quot; client=$remote_addr &#39;<br>               &#39;method=$request_method request=&quot;$request&quot; &#39;<br>               &#39;request_length=$request_length &#39;<br>               &#39;status=$status bytes_sent=$bytes_sent &#39;<br>               &#39;body_bytes_sent=$body_bytes_sent &#39;<br>               &#39;referer=$http_referer &#39;<br>               &#39;user_agent=&quot;$http_user_agent&quot; &#39;<br>               &#39;upstream_addr=$upstream_addr &#39;<br>               &#39;upstream_status=$upstream_status &#39;<br>               &#39;<strong>request_time</strong>=$request_time &#39;<br>               &#39;<strong>upstream_response_time</strong>=$upstream_response_time &#39;<br>               &#39;<strong>upstream_connect_time</strong>=$upstream_connect_time &#39;<br>               &#39;<strong>upstream_header_time</strong>=$upstream_header_time&#39;;<br>  ...<br>}</pre><p>Then in your site config, add the log format param to your access_log:</p><pre>server {<br>  ...<br>  access_log /var/log/nginx/example.com-access.log <strong>apm</strong>;<br>  ...<br>}</pre><p>Restart nginx with command sudo service nginx restart, and you can see new params in your site’s access log file: $ tail -f /var/log/nginx/example.com-access.log</p><pre>18/May/2020:11:03:51 +0700 client=10.20.28.251 method=POST request=&quot;POST /api/hello HTTP/1.1&quot; request_length=865 status=200 bytes_sent=257 body_bytes_sent=62 referer=- user_agent=&quot;okhttp/3.9.0&quot; upstream_addr=127.0.0.1:8803 upstream_status=200 <strong>request_time</strong>=<strong>0.014</strong> <strong>upstream_response_time</strong>=<strong>0.012</strong> <strong>upstream_connect_time</strong>=<strong>0.000</strong> <strong>upstream_header_time</strong>=<strong>0.012</strong></pre><h3>Reference</h3><p><a href="https://www.nginx.com/blog/using-nginx-logging-for-application-performance-monitoring/">Using NGINX Logging for Application Performance Monitoring</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc927325985" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use RabbitMQ]]></title>
            <link>https://thucnc.medium.com/how-to-use-rabbitmq-4e53ad05cee2?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e53ad05cee2</guid>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Mon, 04 May 2020 10:40:08 GMT</pubDate>
            <atom:updated>2020-05-04T10:40:08.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gFwb04MsfqtVB5bY.png" /></figure><h3>Concepts</h3><h4>Exchanges</h4><p>Messages are not published directly to a queue; instead, the producer sends messages to an exchange. An exchange is responsible for routing the messages to different queues with the help of bindings and routing keys.</p><p>A <strong>binding</strong> is a link between a queue and an exchange.</p><p>The <strong>routing key</strong> is a message attribute the exchange looks at when deciding how to route the message to queues (depending on exchange type).</p><p>Exchanges, connections, and queues can be configured with parameters such as <em>durable, temporary,</em> and <em>auto delete</em> upon creation. Durable exchanges survive server restarts and last until they are explicitly deleted. Temporary exchanges exist until RabbitMQ is shut down. Auto-deleted exchanges are removed once the last bound object is unbound from the exchange.</p><p>In RabbitMQ, there are four different types of exchanges that route the message differently using different parameters and bindings setups. Clients can create their own exchanges or use the predefined default exchanges which are created when the server starts for the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*zqPpDQaHVHe_5pmA.png" /></figure><p><strong>Types of Exchanges</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yxRNfBQ_7Av8R1jG.png" /></figure><ul><li><strong>Direct:</strong> The message is routed to the queues whose binding key exactly matches the routing key of the message. For example, if the queue is bound to the exchange with the binding key <em>pdfprocess, a message published to</em> the exchange with a routing key <em>pdfprocess is routed to that queue.</em></li><li><strong>Fanout:</strong> A fanout exchange routes messages to all of the queues bound to it.</li><li><strong>Topic:</strong> The topic exchange does a wildcard match between the routing key and the routing pattern specified in the binding.</li><li><strong>Headers:</strong> Headers exchanges use the message header attributes for routing.</li></ul><h3>Publish and subscribe messages</h3><p>RabbitMQ uses a protocol called AMQP by default. To be able to communicate with RabbitMQ you need a library that understands the same protocol as RabbitMQ. Download the client library for the programming language that you intend to use for your applications.</p><p>Steps to follow when setting up a connection and publishing a message/consuming a message:</p><ol><li>Set up/create a connection object. The username, password, connection URL, port, etc., will need to be specified. A TCP connection will be set up between the application and RabbitMQ when the <em>start</em> method is called.</li><li>Create a channel in the TCP connection, then the connection interface can be used to open a channel through which to send and receive messages.</li><li>Declare/create a queue. Declaring a queue will cause it to be created if it does not already exist. All queues need to be declared before they can be used.</li><li>Set up exchanges and bind a queue to an exchange in subscriber/consumer. All exchanges must be declared before they can be used. An exchange accepts messages from a producer application and routes them to message queues. For messages to be routed to queues, queues must be bound to an exchange.</li><li>In publisher: Publish a message to an exchange<br>In subscriber/consumer: Consume a message from a queue.</li><li>Close the channel and the connection.</li></ol><h4>Python publisher with pika</h4><p>Install pika client</p><pre>pip install pika</pre><p>Sample code:</p><pre><strong>def </strong>rabbit_publish():<br>    print(<strong>&quot;rabbit publish&quot;</strong>)<br><br>    params = pika.URLParameters(<strong>&#39;amqp://guest:guest@localhost:5672&#39;</strong>)<br>    params.socket_timeout = 5<br>    connection = pika.BlockingConnection(params)<br><br>    channel = connection.channel()  <em># start a channel<br>    </em>channel.queue_declare(queue=<strong>&#39;queue1&#39;</strong>)<br><br>    data = {<br>        <strong>&quot;id&quot;</strong>: int(datetime.now().timestamp()) % 100,<strong><br>    </strong>}<br><br>    <em># send a message<br>    </em>channel.basic_publish(exchange=<strong>&#39;&#39;</strong>, routing_key=<strong>&#39;queue1&#39;</strong>, body=json.dumps(data))<br>    print(<strong>&quot;[x] Message sent&quot;</strong>)<br>    connection.close()</pre><h4>Python subscriber with pika</h4><pre><strong>def </strong>rabbit_subscribe():<br>    <strong>def </strong>process(msg):<br>        print(<strong>&quot;Processing&quot;</strong>)<br>        data = json.loads(msg)<br>        print(<strong>&quot; [x] Received:&quot;</strong>, data[<strong>&quot;id&quot;</strong>])<br><br>        time.sleep(3)<br>        print(<strong>f&quot;Processing finished: #{</strong>data[<strong>&#39;id&#39;</strong>]<strong>}&quot;</strong>);<br>        <strong>return True<br><br>    def </strong>callback(ch: BlockingChannel,<br>                 method: pika.spec.Basic.Deliver,<br>                 properties: pika.spec.BasicProperties,<br>                 body: bytes):<em><br>        </em><strong>if </strong>process(body):<strong><br>            </strong>ch.basic_ack(method.delivery_tag, multiple=<strong>False</strong>)<br><br>    print(<strong>&quot;rabbit subscribe&quot;</strong>)<br>    params = pika.URLParameters(<strong>&#39;amqp://guest:guest@localhost:5672&#39;</strong>)<br>    params.socket_timeout = 5<br>    connection = pika.BlockingConnection(params)<br>    channel = connection.channel()<em><br>    </em>channel.basic_consume(<strong>&#39;queue1&#39;</strong>, callback, auto_ack=<strong>False</strong>)<br>    <br>    <em># start consuming (blocks)<br>    </em>channel.start_consuming()<br>    connection.close()</pre><ul><li>auto_ack=False: need to manually acknowledge the message, using channel.basic_ack for example.</li><li>multiple=False: When the multiple field is set to true, RabbitMQ will acknowledge all outstanding delivery tags up to and including the tag specified in the acknowledgement. Like everything else related to acknowledgements, this is scoped per channel. For example, given that there are delivery tags 5, 6, 7, and 8 unacknowledged on channel Ch, when an acknowledgement frame arrives on that channel with delivery_tag set to 8 and multiple set to true, all tags from 5 to 8 will be acknowledged. If multiple was set to false, deliveries 5, 6, and 7 would still be unacknowledged.</li></ul><h3>Types of Exchanges</h3><h4>Direct Exchange</h4><p>A message goes to the queue(s) with the <strong>binding key that exactly matches</strong> the routing key of the message.</p><p>If the message routing key does not match any binding key, the message is discarded.</p><p>The default exchange AMQP brokers must provide for the direct exchange is amq.direct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*KBeJC3bxAy1ZThK-.png" /></figure><h3>Default exchange</h3><p>The default exchange is a pre-declared direct exchange with no name, usually referred by an empty string. When you use default exchange, your message is delivered to the queue with a name equal to the routing key of the message. <strong>Every queue is automatically bound to the default exchange with a routing key which is the same as the queue name</strong>.</p><h3>Fanout Exchange</h3><p>A fanout exchange copies and routes a received message to all queues that are bound to it regardless of routing keys or pattern matching as with direct and topic exchanges. The keys provided will simply be ignored.</p><p>Fanout exchanges can be useful when the same message needs to be sent to one or more queues with consumers who may process the same message in different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*IElLnyi1sTI-3GF6.png" /></figure><p>The default exchange AMQP brokers must provide for the topic exchange is amq.fanout.</p><h3>References</h3><p><a href="https://www.cloudamqp.com/blog/2015-09-03-part4-rabbitmq-for-beginners-exchanges-routing-keys-bindings.html">Part 4: RabbitMQ Exchanges, routing keys and bindings - CloudAMQP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e53ad05cee2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to install RabbitMQ on Ubuntu 18.04]]></title>
            <link>https://thucnc.medium.com/how-to-install-rabbitmq-on-ubuntu-18-04-d002a347764e?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/d002a347764e</guid>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Mon, 04 May 2020 10:37:32 GMT</pubDate>
            <atom:updated>2020-05-06T09:53:26.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/956/0*jrm0FYB4WulUh5u7.png" /></figure><h3>Step 0: Install newest version of Erlang</h3><pre>$ wget -O- <a href="https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc">https://packages.erlang-solutions.com/ubuntu/erlang_solutions.asc</a> | sudo apt-key add -<br>$ echo &quot;deb <a href="https://packages.erlang-solutions.com/ubuntu">https://packages.erlang-solutions.com/ubuntu</a> bionic contrib&quot; | sudo tee /etc/apt/sources.list.d/erlang.list</pre><p>then:</p><pre>sudo apt update<br>sudo apt install erlang</pre><p>Check Erlang version:</p><pre>$ erl -eval &#39;erlang:display(erlang:system_info(otp_release)), halt().&#39;  -noshell</pre><h3>Step 1: Add RabbitMQ Repository To Ubuntu 18.04</h3><pre>$ wget -O- <a href="https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.asc">https://dl.bintray.com/rabbitmq/Keys/rabbitmq-release-signing-key.asc</a> | sudo apt-key add -<br>$ wget -O- <a href="https://www.rabbitmq.com/rabbitmq-release-signing-key.asc">https://www.rabbitmq.com/rabbitmq-release-signing-key.asc</a> | sudo apt-key add -</pre><p>then:</p><pre>$ echo &quot;deb <a href="https://dl.bintray.com/rabbitmq/debian">https://dl.bintray.com/rabbitmq/debian</a> $(lsb_release -sc) main&quot; | sudo tee /etc/apt/sources.list.d/rabbitmq.list</pre><h3>Step 2: Install RabbitMQ Server Ubuntu 18.04 LTS</h3><p>To install RabbitMQ Server Ubuntu 18.04, update apt list, then install rabbitmq-server package:</p><pre>sudo apt update<br>sudo apt install rabbitmq-server</pre><p>Check status:</p><pre>sudo systemctl status  rabbitmq-server.service</pre><p>or</p><pre>sudo service rabbitmq-server status</pre><p>Check RabbitMQ version:</p><pre>sudo rabbitmqctl status | grep RabbitMQ</pre><p>Check if the service is configured to start on boot or not:</p><pre>$ systemctl is-enabled rabbitmq-server.service <br><strong>enabled</strong></pre><p>If it returns disabled, enable it by running:</p><pre>sudo systemctl enable rabbitmq-server</pre><h3>Step 3: Check your firewall</h3><p>After installing RabbitMQ, ufw is enabled and configured by default. If you don’t want that, you can disable it by this command:</p><pre>sudo ufw disable</pre><h3>Step 4: Enable the RabbitMQ Management Dashboard (Optional)</h3><p>You can optionally enable the RabbitMQ Management Web dashboard for easy management.</p><pre>sudo rabbitmq-plugins enable rabbitmq_management</pre><p>The Web service should be listening on TCP port 15672.</p><p>Double if the port is listening:</p><pre>$ ss -tunelp | grep 15672<br>tcp    LISTEN  0        1024               0.0.0.0:15672          0.0.0.0:*      uid:132 ino:1577718 sk:3d &lt;-&gt;</pre><p>By default, the <strong>guest</strong> user exists and can connect only from localhost. You can point your browser to <a href="http://localhost:15672/">http://localhost:15672</a> and login with this user locally with the password “<strong>guest”.</strong></p><p>To be able to login on the network, create an admin user like below:</p><pre>sudo rabbitmqctl add_user <strong>admin</strong> <strong>StrongPassword</strong><br>sudo rabbitmqctl set_user_tags <strong>admin</strong> administrator</pre><h3>RabbitMQ User Management Commands</h3><p>Delete User:</p><pre>sudo rabbitmqctl delete_user user</pre><p>Change User Password:</p><pre>sudo rabbitmqctl change_password user strongpassword</pre><p>Create new Virtualhost:</p><pre>sudo rabbitmqctl add_vhost /my_vhost</pre><p>List available Virtualhosts:</p><pre>sudo rabbitmqctl list_vhosts</pre><p>Delete a virtualhost:</p><pre>sudo rabbitmqctl delete_vhost /myvhost</pre><p>Grant user permissions for vhost:</p><pre>sudo rabbitmqctl set_permissions -p /myvhost user &quot;.*&quot; &quot;.*&quot; &quot;.*&quot;</pre><p>List vhost permissions:</p><pre>sudo rabbitmqctl list_permissions -p /myvhost</pre><p>To list user permissions:</p><pre>sudo rabbitmqctl list_user_permissions user</pre><p>Delete user permissions:</p><pre>sudo rabbitmqctl clear_permissions -p /myvhost user</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d002a347764e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to show current git branch with colors in Bash prompt]]></title>
            <link>https://thucnc.medium.com/how-to-show-current-git-branch-with-colors-in-bash-prompt-380d05a24745?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/380d05a24745</guid>
            <category><![CDATA[command-prompt]]></category>
            <category><![CDATA[colors]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-branch]]></category>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Thu, 24 Oct 2019 04:25:28 GMT</pubDate>
            <atom:updated>2019-10-24T04:25:28.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bm3WGhLRaNtPMKclzYvjtQ.png" /></figure><p>Adding current git branch name in Bash prompt with <em>highlighted color</em> can help to avoid a lot of problems with working on wrong git branches, which is a quite popular scenario to most of the developers sometime. This guide show to do it and explain some underneath concept of the hack.</p><h3>A quick hack</h3><p>Adding this to ~/.bashrc:</p><pre>parse_git_branch() {<br>     git branch 2&gt; /dev/null | sed -e &#39;/^[^*]/d&#39; -e &#39;s/* \(.*\)/(\1)/&#39;<br>}</pre><pre>export PS1=&quot;\u@\h \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ &quot;</pre><p>Restart the terminal, or source ~/.bashrc, and it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*JFi3MdZFFVUhXWmi_AGrWA.png" /></figure><h3>TL; DR</h3><h4>Parse git branch</h4><p>The parse_git_branch function will return the current git branch if we are currently in a git repo directory, otherwise it will return empty string.</p><p>In this function, git branch command will be used. This command will list of local git branches with the * symbol before the current branch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*von0p7N7REbSC_-OTuOjBg.png" /></figure><p>If we are not in a git repo directory, the command will output something like this to stderr:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*_8CONzELqUxEffJ3CzIMrA.png" /></figure><p>We surely don’t want this to appear in our prompt, so we redirect the stderr to /dev/null with this: 2&gt; /dev/null</p><p>The last part is using sed command to extract the current branch name (the line starting with symbol *) from the git branch output.</p><pre>git branch 2&gt; /dev/null <strong>| sed -e &#39;/^[^*]/d&#39; -e &#39;s/* \(.*\)/(\1)/&#39;</strong></pre><p>Where -e &#39;/^[^*]/d&#39; will delete all lines that do not start with symbol *, and the -e &#39;s/* \(.*\)/(\1)/&#39; will replace (substitute) the current branch line (with symbol * and a space at the beginning) with the branch name, putting it in a pair of bracket ().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQNpR2of90GQUZB1B3ACYA.png" /></figure><h4>What is PS1 variable</h4><p>PS1 stands for <em>Prompt String 1</em>. It is the one of the prompt available in Linux/UNIX shell. When you open your terminal, it will display the content defined in PS1 variable in your bash prompt.</p><p>Example of a PS1 string:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*XfkaC0Z69IytKf6TR-2-QQ.png" /></figure><p>To change this prompt, just set new value to PS1 string, for example: PS1=&#39;\u@\h \w &gt; &#39;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*ZReHPIoY-BbB26-mFq70jQ.png" /></figure><p>Where \u, \h and \w are control commands for PS1 string, which stand for username of the current user, the hostname and the current working directory respectively.</p><p><strong>Available control commands for </strong><strong>PS1 string:</strong></p><pre>d - the date in &quot;Weekday Month Date&quot; format (e.g., &quot;Tue May 26&quot;)<br>e - an ASCII escape character (033)<br>h - the hostname up to the first .<br>H - the full hostname<br>j - the number of jobs currently run in background<br>l - the basename of the shells terminal device name<br>n - newline<br>r - carriage return<br>s - the name of the shell, the basename of $0 (the portion following the final slash)<br>t - the current time in 24-hour HH:MM:SS format<br>T - the current time in 12-hour HH:MM:SS format<br>@ - the current time in 12-hour am/pm format<br>A - the current time in 24-hour HH:MM format<br>u - the username of the current user<br>v - the version of bash (e.g., 4.00)<br>V - the release of bash, version + patch level (e.g., 4.00.0)<br>w - Complete path of current working directory<br>W - the basename of the current working directory<br>! - the history number of this command<br># - the command number of this command<br>$ - if the effective UID is 0, a #, otherwise a $<br>nnn - the character corresponding to the octal number nnn<br>\ - a backslash<br>[ - begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt<br>] - end a sequence of non-printing characters</pre><h4>How to set the colors</h4><p>We use this sequence \[\e[32m\] to set the color of the text goes after that sequence, until another color is set. In this sequence, \[ and \] are used to mark the start and end of non-printing characters. Between them, \e denotes an ASCII escape character, and follows by [32m, which is the actual color code.</p><p>All the color codes can be referred here: <a href="https://misc.flogisoft.com/bash/tip_colors_and_formatting">https://misc.flogisoft.com/bash/tip_colors_and_formatting</a></p><p>So, in our hack:</p><pre>export PS1=&quot;\u@\h \[\e[32m\]\w \[\e[91m\]\$(parse_git_branch)\[\e[00m\]$ &quot;</pre><p>the command prompt will start with <em>username@host</em> and a <em>space</em> (\u@\h ), in default terminal color (normally, white text on black background).</p><p>Then comes \[\e[32m\]\w — current working directory (\w) in green ([32m) color, and a space.</p><p>Next is current git branch (\$(parse_git_branch)) if we are in a git repo, in light red ([91m) color.</p><p>The last part of the prompt is symbol $ in default ([00m) color.</p><p>Final result is as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*gx1rATaJ3noDeUAe8gKWLA.png" /></figure><h3>References</h3><ul><li><a href="https://medium.com/@sauravomar01/sed-tutorial-and-basics-383edec3a7a2">Sed: Tutorial and Basics</a></li><li><a href="https://www.linuxnix.com/linuxunix-shell-ps1-prompt-explained-in-detail/">PS1 prompt explained for Linux/Unix - The Linux Juggernaut</a></li><li><a href="https://misc.flogisoft.com/bash/tip_colors_and_formatting">bash:tip_colors_and_formatting - FLOZz&#39; MISC</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=380d05a24745" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert a scanned pdf to text with Linux command line using OCRmyPDF]]></title>
            <link>https://thucnc.medium.com/convert-a-scanned-pdf-to-text-with-linux-command-line-using-ocrmypdf-1a2e8d50277f?source=rss-2a3d883eaace------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2e8d50277f</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[ocrmypdf]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[text-recognition]]></category>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Chi Thuc Nguyen]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 09:06:40 GMT</pubDate>
            <atom:updated>2019-09-26T09:06:40.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*PnUwS_HPj5EBdtdCYcsAqQ.png" /></figure><p><a href="https://github.com/jbarlow83/OCRmyPDF">OCRmyPDF</a> is a free utility that allows you to convert a scanned pdf to text (ocr — optical character recognition). In fact, OCRmyPDF adds an OCR text layer to scanned PDF files over the original one, allowing them to be searched or copy-pasted.</p><h3>Main features</h3><ul><li>Generates a searchable <a href="https://en.wikipedia.org/?title=PDF/A">PDF/A</a> file from a regular PDF</li><li>Places OCR text accurately below the image to ease copy / paste</li><li>Keeps the exact resolution of the original embedded images</li><li>When possible, inserts OCR information as a “lossless” operation without disrupting any other content</li><li>Optimizes PDF images, often producing files smaller than the input file</li><li>If requested deskews and/or cleans the image before performing OCR</li><li>Validates input and output files</li><li>Distributes work across all available CPU cores</li><li>Uses <a href="https://github.com/tesseract-ocr/tesseract">Tesseract OCR</a> engine to recognize more than <a href="https://github.com/tesseract-ocr/tessdata">100 languages</a></li><li>Scales properly to handle files with thousands of pages</li><li>Battle-tested on millions of PDFs</li></ul><h3>Installation</h3><p>Linux, UNIX, and macOS are supported. Windows is not directly supported but there is a Docker image available that runs on Windows.</p><p>Users of Debian 9 or later or Ubuntu 16.10 or later may simply</p><pre>apt-get install ocrmypdf</pre><p>and users of Fedora 29 or later may simply</p><pre>dnf install ocrmypdf</pre><p>and macOS users with Homebrew may simply</p><pre>brew install ocrmypdf</pre><h3>Usage</h3><p>Quick convert a single pdf document</p><pre>ocrmypdf input.pdf output.pdf</pre><p>Convert all pdf files in a folder</p><pre>for f in ./*.pdf; do ocrmypdf &quot;$f&quot; &quot;$(basename &quot;$f&quot; &quot;.pdf&quot;)_ocr.pdf&quot;; done</pre><h3>References</h3><ul><li><a href="https://github.com/jbarlow83/OCRmyPDF">jbarlow83/OCRmyPDF</a></li><li><a href="https://ocrmypdf.readthedocs.io/en/latest/">OCRmyPDF documentation - ocrmypdf 9.0.3.post6+g68c852a documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2e8d50277f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>