<?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 Aijin Yuan (Vince) on Medium]]></title>
        <description><![CDATA[Stories by Aijin Yuan (Vince) on Medium]]></description>
        <link>https://medium.com/@aijinyuan?source=rss-b6a6f3e6f4f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IDPr0WJ-N7TRhMg-.jpeg</url>
            <title>Stories by Aijin Yuan (Vince) on Medium</title>
            <link>https://medium.com/@aijinyuan?source=rss-b6a6f3e6f4f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 03:54:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aijinyuan/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[Excited about Flutter 2 and Farewell to React Native]]></title>
            <link>https://aijinyuan.medium.com/excited-about-flutter-2-and-farewell-to-react-native-48d21e4df9be?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/48d21e4df9be</guid>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 16:51:30 GMT</pubDate>
            <atom:updated>2021-03-12T16:51:30.309Z</atom:updated>
            <content:encoded><![CDATA[<p>I began to use React Native at the end of 2016. In early 2019, I switched to Flutter in the production app and never looked back. In terms of the technology and the ecosystem, Flutter is much better than React Native. (I may write a post about why we should switch to Flutter from React Native.)</p><p>Recently, <a href="https://developers.googleblog.com/2021/03/announcing-flutter-2.html">Flutter 2</a> is officially released! There are a lot of new features. The most exciting feature to me is the web support. Yes, you can use Flutter to write web apps! (If you can’t open flutter.dev, you may have set .dev domain on your machine long time ago. Here is the <a href="https://stackoverflow.com/a/55596083">fix</a>.)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48d21e4df9be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading and Parsing NFC tag on iOS 11]]></title>
            <link>https://aijinyuan.medium.com/reading-and-parsing-nfc-tag-on-ios-11-60f4bc7a11ea?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/60f4bc7a11ea</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[nfc]]></category>
            <category><![CDATA[corenfc]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Mon, 28 Aug 2017 17:11:22 GMT</pubDate>
            <atom:updated>2017-08-28T17:29:46.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*n9Cl8-PKXwDGAcm772aHxg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug0TFMX_nA8QekogCWpdyg.jpeg" /></figure><p>Apple finally opens iPhone’s NFC chip. With iOS 11, apps on iPhone 7 and iPhone 7 plus can read NFC tag using <a href="https://developer.apple.com/documentation/corenfc"><em>Core NFC</em></a>. (Writing is not allowed!) It adds more possibilities to apps. For example, we can use iPhone to tap a NFC tag to read business car, make phone call, open web page, create an email, open another app, or share Wi-Fi. Apple itself uses NFC to pair up HomeKit devices.</p><p><em>Using Core NFC, you can read Near Field Communication (NFC) tags of types 1 through 5 that contain data in the NFC Data Exchange Format (NDEF). </em>Let’s write some code.</p><p>Firstly, import Core NFC library in your iOS project.</p><pre>import CoreNFC</pre><p>Secondly, make YourViewController class conform to NFCNDEFReaderSessionDelegate, like this:</p><pre>class YourViewController: UIViewController, NFCNDEFReaderSessionDelegate {</pre><p>Thirdly, start a NFCNDEFReaderSession when you tap a button.</p><pre>@IBAction func didTapScanNFCTagButton(_ sender: Any) {<br>    let session = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.main, invalidateAfterFirstRead: false)<br>    session.begin()<br>}</pre><p>Lastly, get the NFC NDEF message in the callback.</p><pre>func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {<br>    for message in messages {<br>        for payloadRecord in message.records {<br>            // Handle payloadRecord here<br>        }<br>    }<br>}</pre><p>Here, payloadRecord’s type is NFCNDEFPayload. But as you can see in the following picture, <a href="https://developer.apple.com/documentation/corenfc/nfcndefpayload">Apple’s doc</a> does not give us much detail. typeNameFormat could be nfcWellKnown, media or several other types. But identifier, payload and type are all Data which could be anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeDwCmCUtOtRdCZmRZyqsA.png" /></figure><p>Let’s try to read a simplest NFC tag which contains plain text only. I have empty NFC tags and wrote plain text “hello” into a NFC tag with a free app <a href="https://play.google.com/store/apps/details?id=com.nxp.nfc.tagwriter&amp;hl=en">NFC TagWriter by NXP</a> on an old Android phone Samsung Galaxy Note 3. (Yes, Android phones have NFC for years.). As you can see below, it supports writing many types of data, such as business card, link, email, telephone number, geo location, plain text, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jt7dA1gScJKMScZ6MQ18HA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J3pqeh5Hd0DmajA9gHkHiA.png" /><figcaption>TagWriter and data types it supports</figcaption></figure><p>For the plain text tag, typeNameFormat isnfcWellKnown. Let’s assume identifier, payload and type are all UTF-8 string. After we convert Data to string and print them out, we will see identifier is empty, type is “T”, payload is “enhello”. Obviously “T” means Text. But why is there “en” before “hello”?</p><p>The actual content of payload is the following in hex:</p><pre>02 65 6E 68 65 6C 6C 6F    |.enhello|</pre><p>The structure of plain text payload is more complex than you expected. It consists of 1 status byte, 2 or 5 byte language code, and multiple bytes in UTF-8 or UTF-16. Here is the explaination (from <a href="http://austinblackstoneengineering.com/nfc-p2p-basics/">Austin Blackstone’s post</a>. Many thanks!).</p><pre>|------------------------------|<br>| 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0|<br>|------------------------------|<br>|UTF| 0 | Length of Lang Code  |  1 <strong>byte</strong> Text Record StatusByte<br>|------------------------------|<br>|          Lang Code           |  2 <strong>or</strong> 5 <strong>byte</strong>, multi-<strong>byte</strong> lang code<br>|------------------------------|<br>|             Text             |  Multiple Bytes <strong>in</strong> UTF-8 <strong>or</strong> UTF-16<br>|------------------------------|</pre><p>For our plain text “hello” payload, the first byte is 02 in hex. It is 00000010 in binary. The No. 7 bit is 0 which means the text is encoded in UTF-8. The 0–5 bits show the length of language code. The length is 2. The following 2 bytes “en” is the language code. The real text is the remaining bytes “hello”.</p><p>An NDEF message consists of header and payload. <em>Core NFC</em> parses message header only, but does not parse message payload. You can see even if we only read a plain text NFC tag using Core NFC, it is not so easy as we expected. We can imagine reading NFC tag with other types of payload is much more challenging.</p><p>I decided to accept the challenge. I made <a href="https://github.com/vinceyuan/VYNFCKit">VYNFCKit, an open source NFC NDEF message payload parsing library</a>. VYNFCKit supports parsing almost all data types TagWriter supports, including Business card, Link, WiFi, Email, Telephone number, Geo location, Plain text and SMS. I did not have time to handle Bluetooth and Launch Application. Launch Application seems for Android only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4YDC4qNXIPU8tLeWFpGrsw.gif" /><figcaption>VYNFCKit example app</figcaption></figure><p>Parsing NFC NDEF message payload with VYNFCKit becomes easy.</p><pre>func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {<br>    for message in messages {<br>        for payload in message.records {<br>            guard let parsedPayload = VYNFCNDEFPayloadParser.parse(payload) else {<br>                continue<br>            }<br>            if let parsedPayload = parsedPayload as? VYNFCNDEFTextPayload {<br>                // parsedPayload.text<br>            } else if let parsedPayload = parsedPayload as? VYNFCNDEFURIPayload {<br>                // parsedPayload.uriString<br>            } else if let parsedPayload = parsedPayload as? VYNFCNDEFTextXVCardPayload {<br>                // parsedPayload.text<br>            } else if let sp = parsedPayload as? VYNFCNDEFSmartPosterPayload {<br>                for textPayload in sp.payloadTexts {<br>                    if let textPayload = textPayload as? VYNFCNDEFTextPayload {<br>                        //textPayload.text<br>                    }<br>                }<br>                // sp.payloadURI.uriString<br>            } else if let wifi = parsedPayload as? VYNFCNDEFWifiSimpleConfigPayload {<br>                // wifi.credential.ssid, wifi.credential.networkKey, wifi.credential.macAddress,<br>                // wifi.credential.authType,<br>                // wifi.credential.encryptType<br>            }<br>        }<br>    }<br>}</pre><p>Please refer to <a href="https://github.com/vinceyuan/VYNFCKit">VYNFCKit</a> for detailed steps. Example projects in both Objective-C and Swift are provided. Welcome to try VYNFCKit, report bugs, and send me pull requests. Star ⭐️ it if it helps you a little. 🍺</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60f4bc7a11ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Debugging Tools]]></title>
            <link>https://codeburst.io/react-native-debugging-tools-3a24e4e40e4?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a24e4e40e4</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Sat, 13 May 2017 16:36:28 GMT</pubDate>
            <atom:updated>2018-03-16T16:03:15.583Z</atom:updated>
            <content:encoded><![CDATA[<p>This article introduces how to debug code (logic) and GUI of React Native apps. Originally it was the talk I made at a <a href="https://www.meetup.com/React-Singapore/events/237578363/">React.js/React Native meetup</a> in April 2017. (This article was updated on Mar 17, 2018.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wz41TMMzIl0v41I6QQlLnw.jpeg" /><figcaption>I was talking about debugging React Native apps at the meetup.</figcaption></figure><blockquote>“A great software developer must be a great debugger.”</blockquote><p>The beginners all have a problem. They don’t know how to debug the code. It’s even worse in React Native world. Even if you are an experienced iOS/Android developer, when you begin to learn React Native, you may struggle in debugging React Native apps. The reason is we write Javascript code but Xcode/Android studio doesn’t support debugging Javascript code. I had this problem before. So I spent a lot of time figuring out how to debug code and GUI of React Native apps in the efficient way.</p><h3>Debugging code(logic) with Chrome</h3><p>The simplest way of debugging code is to use Chrome. You don’t need to install any other apps. Press ⌘+D on iOS simulator, ⌘+M on Android emulator, or shake real devices, you will see the in-app developer menu. Tap “Debug JS Remotely”. The Chrome debugger will be opened automatically. You still need to open Developer Tools in Chrome manually. Open source files in the <em>Sources</em> tab, you can set breakpoints here. (<strong>Update on Feb 26, 2018: due to a bug in React Native Android, if the app says it failed to connect the debugger and the URL in Chrome is not </strong><a href="http://localhost:8081/debugger-ui/"><strong>http://localhost:8081/debugger-ui/</strong></a><strong>, change the URL to </strong><a href="http://localhost:8081/debugger-ui/"><strong>http://localhost:8081/debugger-ui/</strong></a><strong>, kill the app, and try again.</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*T77ICgbsNMEIeHcr47oHOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxm3_-lAixnSfitKYE6Kzw.png" /></figure><h3>Debugging code (logic) with Nuclide</h3><p><a href="https://nuclide.io/">Nuclide</a> is a plugin of Atom text editor, made by Facebook. It is very useful to develop React Native apps. <strong>(Update on Feb 26, 2018: Nuclide dropped the support of debugging Node.js and React Native in June 2017 and brought it back in early 2018.)</strong> (Atom is not my favorite editor. But I highly recommend every React Native developer to use Atom+Nuclide.) To use Nuclide to debug React Native app, you need to do the following steps:</p><ol><li>Click the Atom menu Nuclide &gt; Debugger &gt; Show</li><li>Click “Attach debugger…” button.</li><li>In the popup dialog, select “React Native” tab.</li><li>In “Workspace path (should contain package.json):” text field, input your project’s full path.</li><li>Click “Attach” button.</li><li>Open the in-app developer menu. Tap “Debug JS Remotely”. (If you were debugging app using Chrome, you need to “Stop Remote JS Debugging” and close Chrome first.)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2gRMaj_OcMwxn0Mn6nUcA.png" /></figure><p>Then you can set the breakpoints directly in Atom. When a breakpoint is caught, you can check Call Stack, inspect variables. It’s very convenient. You don’t have to leave your editor and open Chrome. You can do all in your editor directly.</p><h3>Debugging with console.log</h3><p>console.log is very useful when we debug web apps. We can also use it in React Native apps. But many people don’t know where the output goes.</p><p>You can see the output in Terminal. Just run command <em>react-native log-ios</em> or <em>react-native log-android</em> in Terminal. You will see something like this. You can download my demo project <a href="https://github.com/vinceyuan/ReactNativeDebugDemo">here</a>. Example 1 is a calculator. But there is a big bug. Uncomment line <a href="https://github.com/vinceyuan/ReactNativeDebugDemo/blob/master/src/ExampleCalculator.js#L49-L51">49–51</a> to enable logs, run the app and open Example 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*eLCH2NsPtCi25FioHlecKg.png" /></figure><p>If you are debugging with Chrome, you can see logs in Chrome console window. Actually we still can use Xcode and Android Studio (to debug native code). We will see logs in output window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*Ot8O3BcmnRF_JkeerVYWfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HV75tHbKfkRodXim4_jhUg.png" /></figure><p>In Nuclide, you can click menu Nuclide &gt; ADB Logcat &gt; Start or Nuclide &gt; iOS Simulator Logs &gt; Start. You will see logs in Console window of Atom. This is my favorite way to check logs. Surprisingly, it’s much faster than Terminal. It usually costs me minutes before I can see logs in Terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*kv2YLtl5kYM4ix9uYB43uQ.png" /></figure><p>There is a way to show the output directly in the app, without using any external command. You can use console.warn() which shows the output in the yellow bar at the bottom of the app. (I just knew it from a colleague on Feb 26, 2018. Thanks!)</p><h3>Use debugger or use console.log?</h3><p>It’s up to you. And you can use both. I don’t always use debugger. I use debugger only when it is really necessary. The reason is I always enable Hot Reloading. Hot reloading is super handy. We can see the changes immediately without restarting the app. But when you are using debugger, it boosts the RAM/CPU usage a lot.</p><p>Sometimes you can’t use debugger. For example, when you want to debug touch-related code, you have to use non-blocking way like console.log, because debugger may terminate your touch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*mgfKUBdIPC7VsqILNPi8hA.gif" /></figure><p>In Example 2 of my demo project, I put a scroll view into a panel which responses to touch using PanResponder. But the scroll view does not work. (The same scroll view works well if it is not in the panel.) That’s because PanResponder is not used correctly. Logs can help you understand PanResponder better. The correct code is commented out. You can uncomment to let scroll view work well. I will not go deeper into PanResponder, because it’s off topic.</p><h3>Debugging GUI</h3><p>App developers usually spend most of their times on GUI. React Native provides built-in inspector. We can open it by pressing ⌘+M / ⌘+D in simulator, and choose “Toggle Inspector”. In Example 3 of the demo project, I created a little bit complex view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*7D5ADwEgA6obIFyqIHPfWg.gif" /></figure><p>You can see in the animated gif, when you open the built-in inspector, you can tap a control and see it’s margin, padding, location, size, and styles, just like what we do in a browser’s developer console. But we cannot change styles with the built-in inspector.</p><p>There are two ways to change styles live. One is enable hot reloading. When you change something in code and save the file, it will be reloaded automatically. The other way is use React Inspector, which is a built-in tool of Nuclide. For unknown reason, the menu item of React Inspector was removed from Nuclide, but we can open it by pressing ⌘+Shift+P in Atom and typing “Inspector”. Then you need to open the built-in inspector of the React Native app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwQbcPIo4zYHapyX_V7d4A.gif" /></figure><p>You can see in the animated gif, the components in React Inspector are grouped in a tree. When the cursor moves to a component, it is highlighted automatically in the app. When we need to understand the structure of other people’s app, this tool helps a lot. Changing style is easy. In this example, I changed the background color easily. You can also add new style with React Inspector.</p><p>If you don’t use Nuclide, you can use <a href="https://github.com/facebook/react-devtools">React DevTools</a> which exists both as a browser extension (for Chrome and Firefox) and a standalone app. The standalone app works with React Native. Actually React Inspector of Nuclide is built on top of React DevTools.</p><h3>Use Xcode to debug GUI</h3><p>In React Native apps, all controls we see in the app are native controls. That’s why this technology is named React <strong>Native</strong>. This means we can utilize the power of Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xp06tFH9xJpP-IptDxaGhA.gif" /></figure><p>After run the app through Xcode, click “Debug View Hierarchy” button, Xcode makes a snap shot of all views. You can inspect the hierarchy in the Navigator window. Click a view, you will see its coordinates in the Size Inspector.</p><p>The coolest feature of Xcode is the 3D view inspector. You can drag the view and move. It shows views in 3D. It is very useful when you need to solve some weird problems in views. For example, in Example 3, a 💩 was missing and I found it with the 3D view inspector. It was covered by other views.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WAAESSc1XKmA6Bjos-5JWw.gif" /></figure><p>You can get the source code of the demo app at <a href="https://github.com/vinceyuan/ReactNativeDebugDemo">https://github.com/vinceyuan/ReactNativeDebugDemo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a24e4e40e4" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/react-native-debugging-tools-3a24e4e40e4">React Native Debugging Tools</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Progress Tracker in React Native]]></title>
            <link>https://aijinyuan.medium.com/implementing-progress-tracker-in-react-native-f4c028328c10?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c028328c10</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Sun, 22 Jan 2017 05:49:37 GMT</pubDate>
            <atom:updated>2017-01-22T06:20:18.035Z</atom:updated>
            <content:encoded><![CDATA[<p>This post shows how I implement a progress tracker (progress bar, progress indicator) in React Native and the lessons I learnt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fz3D8eIDf-Pi-4Wowro9ng.gif" /></figure><h3>First version</h3><p>At the beginning, the design is like this. There are two buttons. There is an arrow between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn2pzjgtAGG6vNTUInzH9g.png" /><figcaption>Original design</figcaption></figure><p>Basically, they are two buttons overlapping. The complex part is the arrow. I use 2 overlapping triangles to build the right part of Button 0 (for the gray edge), and 2 smaller triangles to build the left part of Button 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*iXZAot6CRcIlNt5oh9jJmw.png" /></figure><p>It looks good on both iOS and Android. But on Android, when Button 0 is pressed down, it doesn’t look good. The arrow has a different background. (There is no problem on iOS) The reason is the button is TouchableOpacity. When it is pressed down, it makes subviews half transparent. The arrow consists of two overlapping triangles. So the arrow looks darker when the button is pressed down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-PFF-G-yW3U9METrlkrUw.gif" /></figure><h3>Second Version</h3><p>To remove the extra background of the arrow, I use <a href="https://github.com/react-native-community/react-native-svg">react-native-svg</a> to draw a polyline as the gray edge of the arrow. It’s easy to draw a polyline with react-native-svg. points property of Polyline is a string of all points like &#39;0,0 1,1 0,2&#39;. 0,0 is the first point. 1,1 is the second point. The code is here.</p><pre>&lt;Svg width={ARROW_WIDTH} height={HEIGHT}&gt;<br>  &lt;Polyline fill=&#39;none&#39; stroke=&#39;gray&#39; strokeWidth=&#39;2&#39;<br>    points={&#39;0,-2 &#39; + (ARROW_WIDTH-1) +&#39;,&#39;+ HEIGHT/2<br>    + &#39; 0,&#39; + (HEIGHT+2)} /&gt;<br>&lt;/Svg&gt;</pre><p>No overlapping subviews any more. The progress tracker looks good and works well on both iOS and Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpuXHDppyyVocWUmZbHy_w.gif" /></figure><h3>Third Version</h3><p>The design changed. There could be more than 2 buttons. We need to scroll the progress tracker horizontally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVxpPX6_Duhbd2-ehuZRUQ.png" /><figcaption>New design</figcaption></figure><p>It’s difficult to implement overlapping items in a ScrollView. I wanted to make a button’s subview overflow out of the button by setting negative left value. See pseudo code below.</p><pre>&lt;ScrollView horizontal={true}&gt;<br>  &lt;TouchableOpacity&gt;<br>    &lt;View style={left: -20}&gt;<br>  &lt;/TouchableOpacity&gt;<br>  ...<br>&lt;/ScrollView&gt;</pre><p>Again, it works well on iOS, but doesn’t work on Android. It looks like this on Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgxmVdThXW07t18DT9rg8A.png" /></figure><p>The reason is overflow: visible does not work on Android. Everything will be clipped off. (It’s true on React Native v0.40 and older. React Native v0.41 will make overflow: visible work on Android. Cool!)</p><h3>Fourth Version</h3><p>It’s very frustrating that the third version does not work on Android. I need to use a RelativeLayout instead of a LinearLayout in ScrollView. Finally, I figured out a solution. Add all buttons into a view first, and then add the view into ScrollView. That view is like the content view of UIScrollView. So there is only one item in ScrollView. It works well on both iOS and Android.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fz3D8eIDf-Pi-4Wowro9ng.gif" /></figure><p>You can find the source code <a href="https://github.com/vinceyuan/ReactNativeProgressTracker">here</a>. For the code of the first and second versions, see other branches.</p><p>Another possible solution could be set TouchableOpacity’s margin negative value.</p><h3>Lessons I learnt</h3><ol><li>iOS is the first-class citizen of React Native. Sometimes code works well on iOS but does not work on Android. We have to spend more time on Android. Now I always run code on Android emulator and run on iPhone simulator occasionally.</li><li>Overlapping subviews of TouchableOpacity introduce ugly highlighting effect on Android when the button is pressed down. We should avoid it.</li><li>overflow: visible does not work on Android. (It will change in the future.)</li><li>If you want to do complex things in ScrollView, you can add items into a content view first. It will be easier to implement.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c028328c10" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Profiling memory usage of a Go app]]></title>
            <link>https://aijinyuan.medium.com/profiling-memory-usage-of-a-go-app-599d72b6955e?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/599d72b6955e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Fri, 20 Nov 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-05T04:42:40.426Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Profiling memory usage of a Go app</strong></p><p>net/http/pprof is a powerful package for profiling. This <a href="https://www.youtube.com/watch?v=ydWFpcoYraU">video</a> introduces how to use it to do memory profiling. Let me write down the steps.</p><ol><li>Import the package in your go web project (it doesn’t have to be a web app). Just add this line import _ &quot;net/http/pprof&quot; into your code. (If your app is not a web app, see the links at the end of this post.) If you are using Gin web framework, you need to use the <a href="https://github.com/DeanThompson/ginpprof">pprof wrapper for Gin</a>.</li><li>You can view statistic in browser <a href="http://localhost:8080/debug/pprof/">http://localhost:8080/debug/pprof/</a></li><li>Download the heap profile curl -s http://localhost:8080/debug/pprof/heap &gt; ~/Downloads/base.heap</li><li>After a while, download the current heap profile curl -s http://localhost:8080/debug/pprof/heap &gt; ~/Downloads/current.heap</li><li>Compare two profiles to find the difference.</li></ol><p>go tool pprof --base ~/Downloads/base.heap ~/go/bin/yourapp ~/Downloads/current.heap</p><p>You can show the number of objects by using this option -inuse_objects</p><p>go tool pprof -inuse_objects --base ~/Downloads/base.heap ~/go/bin/yourapp ~/Downloads/current.heap</p><p>6. Now you enter the interactive mode of pprof.</p><p>Use top to view the top entries (memory usage).</p><pre>(pprof) top<br>13356 of -19412 total (  -69%)<br>      flat  flat%   sum%        cum   cum%<br>     10923   -56%   -56%      10923   -56%  runtime.deferproc.func1<br>      1365    -7%   -63%       1365    -7%  runtime.malg<br>       910  -4.7%   -68%        910  -4.7%  math/big.nat.make<br>       158 -0.81%   -69%        158 -0.81%  crypto/tls.(*Conn).readHandshake<br>         0    -0%   -69%          0    -0%  bufio.(*Reader).Peek<br>         0    -0%   -69%          0    -0%  bufio.(*Reader).Read<br>         0    -0%   -69%          0    -0%  bufio.(*Reader).fill<br>         0    -0%   -69%          0    -0%  bufio.(*Writer).Write<br>         0    -0%   -69%          0    -0%  bufio.(*Writer).flush<br>         0    -0%   -69%          0    -0%  bytes.(*Buffer).ReadFrom</pre><p>Use web to visualize the graph though the web browser. Actually it generates a .svg file. You need to set your browser as the default application to open .svg file first.</p><p>You can view the source code! Use list command for functions shown in top. For example, list runtime.deferproc.func1</p><pre>(pprof) list runtime.deferproc.func1<br>Total: -19412<br>ROUTINE ======================== runtime.deferproc.func1 in /usr/local/go/src/runtime/panic.go<br>     10923      10923 (flat, cum)   -56% of Total<br>         .          .     67:   sp := getcallersp(unsafe.Pointer(&amp;siz))<br>         .          .     68:   argp := uintptr(unsafe.Pointer(&amp;fn)) + unsafe.Sizeof(fn)<br>         .          .     69:   callerpc := getcallerpc(unsafe.Pointer(&amp;siz))<br>         .          .     70:<br>         .          .     71:   systemstack(func() {<br>     10923      10923     72:       d := newdefer(siz)<br>         .          .     73:       if d._panic != nil {<br>         .          .     74:           throw(&quot;deferproc: d.panic != nil after newdefer&quot;)<br>         .          .     75:       }<br>         .          .     76:       d.fn = fn<br>         .          .     77:       d.pc = callerpc</pre><p>More resources:</p><p><a href="https://golang.org/pkg/net/http/pprof/">https://golang.org/pkg/net/http/pprof/</a></p><p><a href="https://blog.golang.org/profiling-go-programs">https://blog.golang.org/profiling-go-programs</a></p><p><em>Originally published at </em><a href="http://vinceyuan.github.io/profiling-memory-usage-of-a-go-app"><em>vinceyuan.github.io</em></a><em> on November 20, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599d72b6955e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the SSL root certificates issue]]></title>
            <link>https://aijinyuan.medium.com/solving-the-ssl-root-certificates-issue-a45f01846463?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a45f01846463</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Tue, 08 Sep 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-03T17:11:51.306Z</atom:updated>
            <content:encoded><![CDATA[<p>I created a docker container for a golang app, based on debian 7 image. Everything works well until it visits https. The error is x509: failed to load system roots and no roots provided.</p><p>I thought there might be something that should be configured for golang. But actually, it is nothing about golang. It’s about SSL certificates. For debian, /etc/ssl/certs/ca-certificates.crt is the root certificates. But the offical debian 7 image does not contain it. Installing ca-certificates via apt-get solved the problem. (You can manually copy /etc/ssl/certs/ca-certificates.crt from another linux OS too.)</p><p>Dockerfile:</p><pre>FROM debian:7<br>RUN apt-get update \<br> &amp;&amp; apt-get install -y --force-yes --no-install-recommends \<br>      apt-transport-https \<br>      curl \<br>      ca-certificates \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; apt-get autoremove \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p><em>Originally published at </em><a href="http://vinceyuan.github.io/solving-ssl-root-certificates"><em>vinceyuan.github.io</em></a><em> on September 8, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a45f01846463" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Docker images with tags]]></title>
            <link>https://aijinyuan.medium.com/managing-docker-images-with-tags-def890721d1f?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/def890721d1f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Mon, 08 Jun 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-03T17:11:39.829Z</atom:updated>
            <content:encoded><![CDATA[<p>When you build Docker images many times, you will find it is very necessary to manage images with tags.</p><p>If you build an image without a tag, the default tag ‘latest’ is created automatically.</p><pre>docker build -t company/myimage .</pre><p>The complete name is company/myimage:latest</p><p>When you need to update a new version of company/myimage, you don&#39;t need to create an image company/myimage_v2. You should create an image with the same name and a new tag.</p><pre>docker build -t company/myimage:v2 .</pre><p>And set it latest</p><pre>docker tag -f company/myimage:v2 company/myimage:latest</pre><p>So your new image has two tags: v2 and latest. When you start a container based on company/myimage, company/myimage:latest will be used.</p><p><em>Originally published at </em><a href="http://vinceyuan.github.io/managing-docker-images-with-tags"><em>vinceyuan.github.io</em></a><em> on June 8, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def890721d1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Tricks and Tips]]></title>
            <link>https://aijinyuan.medium.com/docker-tricks-and-tips-2111c13abef0?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2111c13abef0</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Sat, 30 May 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-03T17:14:34.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I deployed my node.js app, Redis, Postgres, Nginx with Docker and wrote a <a href="https://medium.com/@vinceyuan/deploying-a-web-app-redis-postgres-and-nginx-with-docker-ccb7ccfbe8c4#.bmjsempmn">tutorial</a>. I want to share you with some tricks and tips about Docker.</p><h3>Choose Debian as the base image.</h3><p>Debian image is much smaller than other OS images. It is recommended in Docker’s official <a href="https://docs.docker.com/articles/dockerfile_best-practices/#from">best practices</a>. A problem is the packages in Debian apt are not always latest. I think Debian only likes the very stable versions. You may need to spend some time installing the proper packages.</p><h3>Choose the same base image for all your own images.</h3><p>If your images are based on the same base image, it will save you a lot of disk spaces. Your images share the same base image on disk.</p><h3>Build images for each step.</h3><p>If your node.js app needs to access Redis, Postgres, you’d better create a Redis client image, a Postgres client image, a node.js image, and your app image. Each image is based on the previous one. If you have 2 node.js app, you don’t need to install Redis, Postgres clents, node.js again, just use the node.js image as the base.</p><h3>Put your important data at the host instead of the container.</h3><p>If a container is deleted, all files in the container will be deleted too. Use volume for the important data.</p><h3>Be very careful with the image whose Dockerfile has VOLUME.</h3><p>If you use this image without providing a folder of the host, the container will create a volume at /var/lib/docker/vfs/dir/. When the container is deleted, that volume will not be deleted automatically. If big data is stored there, it will use up your disk space. You can install this useful tool <a href="https://github.com/cpuguy83/docker-volumes">https://github.com/cpuguy83/docker-volumes</a> on your host to find and remove the dangling volumes.</p><h3>You can run docker without sudo.</h3><pre># Add theuser to docker group to run docker as a non-root user<br># MUST logout and re-login to let it effective<br>usermod -aG docker theuser</pre><h3>Delete the unnecessary files in the Dockerfile to save disk space.</h3><p>For example,</p><pre>FROM myredisclient<br>RUN apt-get update \<br> &amp;&amp; apt-get install -y wget \<br> &amp;&amp; echo &#39;deb <a href="http://apt.postgresql.org/pub/repos/apt/">http://apt.postgresql.org/pub/repos/apt/</a> wheezy-pgdg main&#39; &gt;&gt; /etc/apt/sources.list.d/pgdg.list \<br> &amp;&amp; wget --no-check-certificate --quiet -O - <a href="https://www.postgresql.org/media/keys/ACCC4CF8.asc">https://www.postgresql.org/media/keys/ACCC4CF8.asc</a> | apt-key add - \<br> &amp;&amp; apt-get update \<br> &amp;&amp; apt-get install -y --force-yes postgresql-client \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; apt-get autoremove \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p><em>Originally published at </em><a href="http://vinceyuan.github.io/docker-tricks-and-tips"><em>vinceyuan.github.io</em></a><em> on May 30, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2111c13abef0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restoring/Backing up Postgres Database in a Docker Container]]></title>
            <link>https://aijinyuan.medium.com/restoring-backing-up-postgres-database-in-a-docker-container-204547a60b1e?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/204547a60b1e</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Fri, 29 May 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-03T17:13:17.318Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@vinceyuan/deploying-a-web-app-redis-postgres-and-nginx-with-docker-ccb7ccfbe8c4#.bmjsempmn">previous tutorial</a>, I show you how to deploy a web app, Redis, Postgres, Nginx with Docker. This post shows you how to restore and backup Postgres database which is running in a Docker container. You can get all source code at <a href="https://github.com/vinceyuan/DockerizingWebAppTutorial">https://github.com/vinceyuan/DockerizingWebAppTutorial</a>.</p><p>I use pg_dump to dump a database to a text file. And then zip and upload it to Amazon S3 with a handy command line tool s3cmd. In this tutorial, I can&#39;t provide access_key and secret_key of S3. So you may not really run it until you get your own.</p><p>Let’s install s3cmd on the host.</p><pre>apt-get install -y s3cmd</pre><p>Run s3cmd to configure. You should input your access_key and secret_key of S3. It creates .s3cfg at your home directory.</p><h3>Restore</h3><p>In the previous tutorial, after running Postgres in a container, we should restore database from the backup. We need to get the backup first.</p><pre>cd /mydata &amp;&amp; mkdir db_restore &amp;&amp; cd db_restore</pre><p>List backup files in your s3.</p><pre>s3cmd ls s3://your_db_dumps/</pre><p>Download a backup file and unzip.</p><pre>s3cmd get s3://db_dumps/dump2015-05-22T09:15:13+0800.txt.gz<br>gunzip dump2015-05-22T09\:15\:13+0800.txt.gz</pre><p>Run a container with Postgres client to restore db from dump.</p><pre>docker run -d --name myredispgclient --link mypostgres:postgres -v /mydata/db_restore/:/tmp/ -i -t myredispgclient /bin/bash</pre><p>If it does not show the console of the container, run this to get it</p><pre># docker exec -i -t myredispgclient bash $ env | grep POSTGRES_<br>$ psql -h $POSTGRES_PORT_5432_TCP_ADDR -p $POSTGRES_PORT_5432_TCP_PORT -U postgres<br>&gt; \l # List all databases. Make sure mynodeappdb exists<br>&gt; \q # Quit<br>$ psql -h $POSTGRES_PORT_5432_TCP_ADDR -p $POSTGRES_PORT_5432_TCP_PORT -U postgres -d mynodeappdb &lt; /tmp/dump2015-05-22T09\:15\:13+0800.txt<br>$ exit # Exit the console of the container<br># docker stop myredispqclient</pre><h3>Backup</h3><p>Let’s build mys3cmd image which has s3cmd 1.0 installed. The latest version is 1.5.2. But 1.5.2 fails to upload big files for me. So I have to use 1.0. This is the Dockerfile. It is based on myredispgclient image.</p><pre>FROM myredispgclient<br>RUN apt-get update \<br> &amp;&amp; wget -O- -q <a href="http://s3tools.org/repo/deb-all/stable/s3tools.key">http://s3tools.org/repo/deb-all/stable/s3tools.key</a> | apt-key add - \<br> &amp;&amp; wget -O/etc/apt/sources.list.d/s3tools.list <a href="http://s3tools.org/repo/deb-all/stable/s3tools.list">http://s3tools.org/repo/deb-all/stable/s3tools.list</a> \<br> &amp;&amp; apt-get update \<br> &amp;&amp; apt-get install -y --force-yes --no-install-recommends s3cmd=1.0.0-4 \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; apt-get autoremove \<br> &amp;&amp; rm -rf /var/lib/apt/lists/\*</pre><p>Build it.</p><pre>cd /DockerizingWebAppTutorial/dockerfiles/mys3cmd<br>docker build -t mys3cmd .</pre><p>Let’s build mydbbackup2s3 image for backing up. I tried many times to write a working Dockerfile for mydbbackup2s3. That&#39;s why I create mys3cmd image. With mys3cmd image, it doesn&#39;t need to download and install s3cmd when I re-build mydbbackup2s3 again and again. In the Dockerfile of mydbbackup2s3, we copied .pgpass and .s3cfg to /root/ (You need to provide .s3cfg yourself). .pgpass stores the password of the database and we have to chmod 600 for it. dump_db_and_upload.sh is a script I wrote to dump, zip, and upload the backup to s3.</p><pre>FROM mys3cmd</pre><pre>COPY .pgpass /root/<br>COPY .s3cfg /root/<br>COPY dump_db_and_upload.sh /root/</pre><pre>RUN chmod 600 /root/.pgpass</pre><pre>VOLUME /db_dumps</pre><pre>CMD [&quot;/root/dump_db_and_upload.sh&quot;]</pre><p>The first postgres in .pgpass is the linked container.</p><pre>postgres:5432:mynodeappdb:postgres:postgres</pre><p>dump_db_and_upload.sh</p><pre>#!/bin/bash<br># A script to dump db and compress it and then upload the file to S3.<br># should change mode like &#39;chmod 777 dump_db_and_sync.sh&#39;</pre><pre>FILENAME=$(TZ=Asia/Hong_Kong date +&quot;dump%Y-%m-%dT%H:%M:%S+0800.txt.gz&quot;)<br>FULLDIR=&quot;/db_dumps/&quot;<br>FULLPATH=&quot;$FULLDIR$FILENAME&quot;<br>S3PATH=&quot;s3://db_dumps/&quot;<br>echo &quot;Begin to dump mynodeappdb to $FULLPATH&quot;</pre><pre># We don&#39;t use $POSTGRES_PORT_5432_TCP_ADDR for host, but use postgres which is linked<br># $POSTGRES_PORT_5432_TCP_ADDR will change, but link name postgres does not change.<br># We also use the link name postgres in .pgpass</pre><pre>pg_dump -h postgres -U postgres mynodeappdb | gzip &gt; $FULLPATH<br>echo &quot;Done&quot;<br>echo &quot;Begin to upload the dump to $S3PATH&quot;<br>s3cmd put $FULLPATH $S3PATH<br>echo &quot;Done&quot;<br>echo &quot;Delete the local dump&quot;<br>rm $FULLPATH<br>echo &quot;Finished dump and upload&quot;</pre><p>Build the image.</p><pre>cd /DockerizingWebAppTutorial/dockerfiles/mydbbackup2s3<br>docker build -t mydbbackup2s3 .</pre><p>Run the container. We don’t add --restart=always here.</p><pre>docker run -d --name mydbbackup2s3 --link mypostgres:postgres -v /mydata/db_dumps:/db_dumps mydbbackup2s3</pre><p>It should dump database and backup immediately. The container will quit after backing up is done.</p><h3>Auto-backup</h3><p>We should backup the database regularly and automatically. Let’s create a cron job by running this command:</p><pre>crontab -e</pre><p>Input the following lines, save and quit. It will run mydbbackup2s3 container to backup database every Tuesday.</p><pre>#MIN (0-59)  HOUR (0-23)  DoM (1-31)  MONTH (1-12)  DoW (0-7)     CMD<br>#Dump pophub db and upload to S3 every Tuesday at 10:00 Hong Kong time<br>     0            2           *           *            2          docker start mydbbackup2s3</pre><p>Here are some <a href="http://vinceyuan.github.io/docker-tricks-and-tips/">tips</a> about Docker.</p><p><em>Originally published at </em><a href="http://vinceyuan.github.io/restoringbacking-up-postgres-database"><em>vinceyuan.github.io</em></a><em> on May 29, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=204547a60b1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Web App, Redis, Postgres and Nginx with Docker]]></title>
            <link>https://aijinyuan.medium.com/deploying-a-web-app-redis-postgres-and-nginx-with-docker-ccb7ccfbe8c4?source=rss-b6a6f3e6f4f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccb7ccfbe8c4</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Aijin Yuan (Vince)]]></dc:creator>
            <pubDate>Fri, 29 May 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-03T17:16:04.228Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial introduces how to deploy a web app, Redis, Postgres and Nginx with Docker on the same server. In this tutorial, the web app is a node.js(express) app. We use Redis as a cache store, Postgres as the database, and Nginx as the reverse proxy server. You can get all source code at <a href="https://github.com/vinceyuan/DockerizingWebAppTutorial">https://github.com/vinceyuan/DockerizingWebAppTutorial</a>.</p><h3>Why Docker</h3><p>Docker is a virtualization technology. The key feature I like most is it provides resource isolation. The traditional way of building a (low-traffic) website is we install the web app, cache, database, Nginx directly on a server. It’s not easy to change the settings or the content a lot, because they are in the same environment. Changing one may impact others. With Docker, we can put each service in a container. It keeps the host server very clean. We can easily create/delete/change/re-create containers.</p><h3>Install Docker on the host</h3><p>Docker runs on a 64-bit Linux OS only. If your Linux is 32-bit, you have to re-install the 64-bit version. My original OS was 32-bit CentOS. Now I am using 64-bit Debian 8. The main reason I choose Debian is its distribution size is small and Docker recommends it in <a href="https://docs.docker.com/articles/dockerfile_best-practices/#from">Best Practices</a>(it’s ridiculous that almost all examples at docker.com use ubuntu). Actually the host’s OS can be different to the container’s OS. I choose Debian instead of 64-bit CentOS because I don’t want to spend any time on the differences. For example, the package management tools on Debian and CentOS are different. One is apt, the other is yum.</p><p>Currently, Docker’s <a href="https://docs.docker.com/installation/debian/#installation">official installation</a> on Debian 8 does not work. You need to run the following commands as root. theuser is the user of host OS.</p><pre>sudo su<br>curl -sSL <a href="https://get.docker.com/">https://get.docker.com/</a> | sh<br># Add theuser to docker group to run docker as a non-root user<br># MUST logout and re-login to let it effective<br>usermod -aG docker theuser<br># Start docker service<br>systemctl enable docker.service<br>systemctl start docker.service</pre><h3>Prepare</h3><pre>cd / git clone<br><a href="https://github.com/vinceyuan/DockerizingWebAppTutorial.git">https://github.com/vinceyuan/DockerizingWebAppTutorial.git</a></pre><p>The folder /DockerizingWebAppTutorial contains all we need. mynodeapp is a very simple node.js (express) app. It just reads a number from Redis, and gets a query result from Postgres. There are several Dockerfiles in the dockerfiles folder. We will use them to build images.</p><p>Create folders:</p><pre>cd / &amp;&amp; mkdir mydata &amp;&amp; cd myata<br>mkdir redis_data &amp;&amp; mkdir postgres_data &amp;&amp; mkdir nginx_data<br>root@pophubserver:/mydata# mkdir log_mynodeapp &amp;&amp; mkdir log_nginx</pre><p>Let’s run the first container.</p><h3>Redis</h3><p>We use the official Redis image. Run it directly with this command:</p><pre>docker run -d -v /mydata/redis_data:/data --name myredis --restart=always redis</pre><p>-v /mydata/redis_data:/data means we mount a folder /mydata/redis_data of the host as a volume /data in a container. Nginx will save dump.rdb at /mydata/redis_data in the host. If we don&#39;t mount a volume, Nginx will save dump.rdb in the container. When this container is deleted, dump.rdb will be deleted too. So we should always mount a volume for the important data e.g. database file, logs. --name myredis means we name this container myredis --restart=always means the container will restart after it quits unexpectedly. It also makes the container start automatically after the server reboots.</p><p>That command outputs:</p><pre>$ docker run -d -v /mydata/redis_data:/data --name myredis --restart=always redis<br>Unable to find image &#39;redis:latest&#39; locally<br>latest: Pulling from redis<br>7a3e804ed6c0: Pull complete <br>b96d1548a24e: Pull complete <br>5ba9a5b9710f: Pull complete <br>37f07aacbfe5: Pull complete <br>ec7f3a6b5dc6: Pull complete <br>499b313c4d4e: Pull complete <br>4416945429c6: Pull complete <br>0daf71066555: Pull complete <br>1f86439b265d: Pull complete <br>9e6288fa06c0: Pull complete <br>3c083702089f: Pull complete <br>71cc4c7123fc: Pull complete <br>91e5e3734476: Pull complete <br>8d7fb9bd09ab: Pull complete <br>e6b7cf8bf1b1: Pull complete <br>96182c1bd121: Pull complete <br>4b7672067154: Already exists <br>redis:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.<br>Digest: sha256:01b59520487a9ada4b8e31558c0580930a4e5f2a565a1cb85b66efe7c6ce810d<br>Status: Downloaded newer image for redis:latest<br>a96b6d2555e9f9fb1f70fea60f8cf75326cd331ebef9d4b667e322cea899d48c</pre><p>It downloads redis:latest image from Docker Hub. Let&#39;s check if myredis container is running.</p><pre>$ docker ps -a<br>CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS               NAMES<br>a96b6d2555e9        redis:latest        &quot;/entrypoint.sh redi   16 minutes ago      Up 16 minutes       6379/tcp            myredis</pre><p>We can see myredis is running.</p><p>We need to run redis-cli in this container to set a value in Redis.</p><pre>$ docker exec -i -t myredis bash<br>root@a96b6d2555e9:/data# redis-cli<br>127.0.0.1:6379&gt; set number 1<br>OK<br>127.0.0.1:6379&gt; save<br>OK<br>127.0.0.1:6379&gt; exit<br>root@a96b6d2555e9:/data# exit</pre><h3>Postgres</h3><p>We use the official Postgres image too. Just run it directly.</p><pre>docker run -d --name mypostgres -e POSTGRES_PASSWORD=postgres -v /mydata/postgres_data:/var/lib/postgresql/data --restart=always postgres</pre><p>-e POSTGRES_PASSWORD=postgres means we set the environment variable POSTGRES_PASSWORD to postgres.</p><p>-v /mydata/postgres_data:/var/lib/postgresql/data means we mount /mydata/postgres_data as a volume. This is very important. It&#39;s safe to keep database files in the host.</p><p>Create mynodeappdb:</p><pre>$ docker exec -i -t mypostgres bash<br>root@11602c44f706:/# psql -U postgres<br>psql (9.4.2)<br>Type &quot;help&quot; for help.<br>postgres=# create database mynodeappdb;<br>CREATE DATABASE<br>postgres=# \q<br>root@11602c44f706:/# exit</pre><p>We can see mypostgres and myredis are running.</p><pre>$ docker ps -a<br>CONTAINER ID        IMAGE               COMMAND                CREATED              STATUS              PORTS               NAMES<br>11602c44f706        postgres:latest     &quot;/docker-entrypoint.   About a minute ago   Up About a minute   5432/tcp            mypostgres          <br>a96b6d2555e9        redis:latest        &quot;/entrypoint.sh redi   32 minutes ago       Up 32 minutes       6379/tcp            myredis</pre><h3>Redis client and Postgres client</h3><p>The Dockerfile for redis client:</p><pre>FROM debian:7</pre><pre>RUN apt-get update \<br> &amp;&amp; apt-get install -y redis-server \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; apt-get autoremove \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*<br>RUN service redis-server stop</pre><p>It’s based on debian:7. It actually installs both redis server and client. But we only need the client. So it stops redis-server.</p><p>Build it:</p><pre>cd /DockerizingWebAppTutorial/dockerfiles/myredisclient<br>docker build -t myredisclient .</pre><p>The Dockerfile for Postgres client:</p><pre>FROM myredisclient</pre><pre>RUN apt-get update \<br> &amp;&amp; apt-get install -y wget \<br> &amp;&amp; echo &#39;deb <a href="http://apt.postgresql.org/pub/repos/apt/">http://apt.postgresql.org/pub/repos/apt/</a> wheezy-pgdg main&#39; &gt;&gt; /etc/apt/sources.list.d/pgdg.list \<br> &amp;&amp; wget --no-check-certificate --quiet -O - <a href="https://www.postgresql.org/media/keys/ACCC4CF8.asc">https://www.postgresql.org/media/keys/ACCC4CF8.asc</a> | apt-key add - \<br> &amp;&amp; apt-get update \<br> &amp;&amp; apt-get install -y --force-yes postgresql-client \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; apt-get autoremove \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><p>It’s based on myredisclient, because our web app needs to access both redis and postgres. The annoying thing is the default postgresql-client in Debian apt is a very old version (pg_dump will not work, because the version does not match the server&#39;s version). This Dockerfile installs the latest version (currently 9.4).</p><p>Build it</p><pre>cd /DockerizingWebAppTutorial/dockerfiles/myredispgclient<br>docker build -t myredispgclient .</pre><p>We can see there are 5 images in the host.</p><pre>$ docker images<br>REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE<br>myredispgclient     latest              78b18351c561        6 minutes ago       132.5 MB<br>myredisclient       latest              bb2ac4846244        8 minutes ago       87.7 MB<br>postgres            latest              1636d90f0662        2 days ago          214 MB<br>redis               latest              4b7672067154        4 days ago          111 MB<br>debian              7                   b96d1548a24e        9 days ago          84.97 MB</pre><h3>Node.js</h3><p>Let’s build a Node.js image. In the Dockerfile for mynodejs image, we install node.js, express, forever and then set NODE_ENV production. In this example, I am not using the latest version.</p><pre>FROM myredispgclient</pre><pre>RUN apt-get update \<br> &amp;&amp; apt-get install -y --force-yes --no-install-recommends \<br>      apt-transport-https \<br>      build-essential \<br>      curl \<br>      ca-certificates \<br>      git \<br>      lsb-release \<br>      python-all \<br>      rlwrap \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; apt-get autoremove \<br> &amp;&amp; rm -rf /var/lib/apt/lists/*</pre><pre>RUN curl <a href="https://deb.nodesource.com/node/pool/main/n/nodejs/nodejs_0.10.30-1nodesource1~wheezy1_amd64.deb">https://deb.nodesource.com/node/pool/main/n/nodejs/nodejs_0.10.30-1nodesource1~wheezy1_amd64.deb</a> &gt; node.deb \<br> &amp;&amp; dpkg -i node.deb \<br> &amp;&amp; rm node.deb</pre><pre>RUN npm install -g express@3.4.7 \<br> &amp;&amp; npm install -g forever \<br> &amp;&amp; npm cache clear</pre><pre>ENV NODE_ENV production</pre><p>Build it.</p><pre>cd /DockerizingWebAppTutorial/dockerfiles/mynodejs<br>docker build -t mynodejs .</pre><h3>mynodeapp</h3><p>Then we build an image for mynodeapp. In Dockerfile, we run npm install, and use forever to run the node.js app. We don’t use forever start, because we don’t run it as a daemon (otherwise, the container will quit immediately).</p><pre>FROM mynodejs</pre><pre>COPY . /src<br>RUN cd /src &amp;&amp; npm install<br>VOLUME /log<br>CMD [&quot;forever&quot;, &quot;-l&quot;, &quot;/log/forever.log&quot;, &quot;-o&quot;, &quot;/log/out.log&quot;, &quot;-e&quot;, &quot;/log/err.log&quot;, &quot;/src/app.js&quot;]</pre><p>Build it</p><pre>cd /DockerizingWebAppTutorial/mynodeapp<br>docker build -t mynodeapp .</pre><p>Actually we can merge these 4 Dockerfiles into one to create one image. I build 4 images for re-using images. For example, if we want to build an image for another node.js app, we can write a Dockerfile based on mynodejs image. If we want to replace node.js with Go, we can write a Dockerfile based on myredispgclient.</p><p>The core code of mynodeapp:</p><pre>var conString;</pre><pre>if (&#39;development&#39; == app.get(&#39;env&#39;)) {<br>  app.use(express.errorHandler());<br>  conString = &quot;postgres://vince:<a href="http://twitter.com/localhost/mynodeappdb">@localhost/mynodeappdb</a>&quot;; // Use your db, user and password<br>} else {<br> conString = &quot;postgres://postgres:postgres@localhost/mynodeappdb&quot;; // Use your db, user and password<br>}</pre><pre>var pgClient = new pg.Client(conString);</pre><pre>pgClient.connect(function(err) {<br>  if(err) return console.error(&#39;Could not connect to postgres&#39;, err);<br>  console.log(&#39;Connected to postgres&#39;);<br>});</pre><pre>var redisClient = redis.createClient(6379, &#39;127.0.0.1&#39;, {})</pre><pre>app.get(&#39;/&#39;, function(req, res) {<br>  pgClient.query(&#39;SELECT NOW() AS &quot;theTime&quot;&#39;, function(err1, result) {<br>    redisClient.get(&quot;number&quot;, function(err2, reply) {<br>      res.render(&#39;index&#39;, { pgTime: result.rows[0].theTime, number: reply });<br>    });<br>  }); // Errors Ignored in this example. You should check errors in a real project. <br>});</pre><pre>http.createServer(app).listen(app.get(&#39;port&#39;), function() {<br>  console.log(&#39;Express server listening on port &#39; + app.get(&#39;port&#39;));<br>});</pre><p>There is a problem. We are using localhost or 127.0.0.1 for redis and postgres&#39; host address. It works only when they are installed on the same server. But now they are in different containers. Even if we use --link, we still cannot access them via localhost and 127.0.0.1. We can use the following code to get correct host and port.</p><pre>var redis_host = process.env.REDIS_PORT_6379_TCP_ADDR || &#39;127.0.0.1&#39;;<br>var redis_port = process.env.REDIS_PORT_6379_TCP_PORT || 6379;<br>var db_host = process.env.POSTGRES_PORT_5432_TCP_ADDR || &#39;localhost&#39;;</pre><p>REDIS_PORT_6379_TCP_ADDR is created by Docker if you run a container with --link myredis:redis. You can get Postgres user account, password, port from the environment variables too.</p><p>Run a container based on mynodeapp image. We also name the container mynodeapp. You can rename it whatever you like.</p><pre>docker run -d --name mynodeapp --link mypostgres:postgres --link myredis:redis -v /mydata/log_mynodeapp:/log -p 3000:3000 --restart=always mynodeapp</pre><p>By default, each container is isolated. --link allows a container access another container. --link mypostgres:postgres means we can access mypostgres container with the alias postgres just like localhost for 127.0.0.1. -v /mydata/log_mynodeapp:/log mounts a volume. We want to keep logs in the host. -p 3000:3000 maps host&#39;s port 3000 to container&#39;s port 3000. It is not mandatory. But with it, we can use curl localhost:3000 in the host to check if mynodeapp container runs correctly.</p><pre>$ curl localhost:3000<br>&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;&lt;/title&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;/stylesheets/style.css&quot;&gt;&lt;/head&gt;&lt;body&gt;&lt;H1&gt;mynodeapp&lt;/H1&gt;&lt;p&gt;Number from Redis: 1&lt;/p&gt;&lt;p&gt;Time from Postgres: Fri May 29 2015 09:47:54 GMT+0000 (UTC)&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre><p>The web app runs correctly in the container.</p><h3>Nginx</h3><p>Now we install Nginx. In the Dockerfile, we make directory /mynodeapp/public. A folder in the host will be mounted here.</p><pre>FROM nginx</pre><pre># Create folder for static files<br>RUN mkdir /mynodeapp &amp;&amp; mkdir /mynodeapp/public</pre><pre># copy sslcert files to /etc/nginx/ for https<br>#COPY mydomain.* /etc/nginx/</pre><pre># copy conf<br>COPY nginx-docker.conf /etc/nginx/nginx.conf</pre><p>In nginx-docker.conf, we use mynodeapp for the server address, because it is linked.</p><pre>    upstream mynodeapp_upstream {<br>        server mynodeapp:3000;<br>        keepalive 64;<br>    }</pre><p>Build the image and run the container.</p><pre>cd /DockerizingWebAppTutorial/dockerfiles/mynginx<br>docker build -t mynginx .</pre><p>Run mynginx container.</p><pre>docker run -d --name mynginx --link mynodeapp:mynodeapp -v /mydata/nginx_data:/var/cache/nginx -v /mydata/log_nginx:/var/log/nginx -v /DockerizingWebAppTutorial/mynodeapp/public:/mynodeapp/public -p 80:80 -p 443:443 --restart=always mynginx</pre><p>--link mynodeapp:mynodeapp means we link mynodeapp container to mynginx container. We don&#39;t link myredis and mypostgres because mynginx does not access them directly. We also mount 2 folders for logging. -p 443:443 is for https. However, this example does not provide ssl certificate files.</p><p>Run curl localhost and curl localhost/stylesheets/style.css to check if mynginx runs correctly.</p><pre># curl localhost<br>&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;&lt;/title&gt;&lt;link rel=&quot;stylesheet&quot; href=&quot;/stylesheets/style.css&quot;&gt;&lt;/head&gt;&lt;body&gt;&lt;H1&gt;mynodeapp&lt;/H1&gt;&lt;p&gt;Number from Redis: 1&lt;/p&gt;&lt;p&gt;Time from Postgres: Fri May 29 2015 10:12:35 GMT+0000 (UTC)&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</pre><pre>root@pophubserver:/DockerizingWebAppTutorial/dockerfiles/mynginx# <br>root@pophubserver:/DockerizingWebAppTutorial/dockerfiles/mynginx# curl localhost/stylesheets/style.css<br>body {<br>  padding: 50px;<br>  font: 14px &quot;Lucida Grande&quot;, Helvetica, Arial, sans-serif;<br>}</pre><pre>a {<br>  color: #00B7FF;<br>}</pre><p>Now we finished deploying a web app, Redis, Postgres and Nginx with Docker. It took me a lot of time to really deploy my real app with Docker. Luckily I tested in a VirtualBox VM. I can delete/create images/containers back and forth easily with Docker.</p><p>An important part is missing. That’s restoring and backing up database. I will show you in <a href="https://medium.com/@vinceyuan/restoring-backing-up-postgres-database-in-a-docker-container-204547a60b1e#.rkc1nludr">another tutorial</a>. Here are some <a href="https://medium.com/@vinceyuan/docker-tricks-and-tips-2111c13abef0#.bflhnqo10">tips</a> about Docker.</p><p><em>Originally published at </em><a href="http://vinceyuan.github.io/deploying-web-app-redis-postgres-and"><em>vinceyuan.github.io</em></a><em> on May 29, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccb7ccfbe8c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>