Setting up a LAMP server on Ubuntu 17.04, and enabling remote access to MySQL

I originally wrote this on my site, https://blog.crazy.technology, which I will be taking down in a few days.

Introduction

This post records some steps I took to set up a LAMP server on Ubuntu, and how I configured MySQL to allow remote access with MySQL workbench.

Please note that this is not meant to be an exhaustive guide, and absolutely no security measures are in place.

I used a Google Cloud VM, but I’m pretty sure this could be applied to a home server as well. Just remember to open to required ports on your router and forward them appropriately.

Where possible, I will credit the original source of information, and paste code snippets to facilitate replication of this. I have left out most of the text from the guides I referenced. If you’d like to understand in depth what each line of code does, please refer to the original links.

Machine Configuration

Google Cloud Platform

  • f1-micro (1 vCPU, 0.6 GB memory)
  • 10GB HDD
  • Ubuntu 17.04

Allows:

  • Http / Https traffic
  • Open port 3306 (for MySQL remote access)

LAMP Server Setup

Reference: https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-16-04

Installing Apache and making some changes to configuration

Install Apache

sudo apt-get update
sudo apt-get install apache2

Update Apache config file

sudo nano /etc/apache2/apache2.conf

Update ServerName server_domain_or_IP

sudo systemctl restart apache2

Check if UFW has an application profile for Apache like so:

sudo ufw app list

Apache Full profile should show that it enables traffic to ports 80 and 443:

sudo ufw app info "Apache Full"

Allow incoming traffic for this profile:

sudo ufw allow in "Apache Full"

Accessing http://your_server_IP_address should yield a generic index.html page

Install MySQL

Install MySQL server

sudo apt-get install mysql-server

Update security settings

mysql_secure_installation //Configure security settings your way

Install PHP

Install PHP

sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql

Test PHP

sudo nano /var/www/html/info.php
<?php
phpinfo();
?>

Access via localhost/info.php. You should see your current php configuration displayed.

Update: Follow this link if doing on Raspberry Pi
https://www.stewright.me/2016/03/turn-raspberry-pi-3-php-7-powered-web-server/

Configuring MySQL for Remote Access via MySQL Workbench

This assumes you already have installed MySQL Workbench on the remote computer which is not on the same local network. Also, port 3306 should be open for this to work.
Check your port with netstat -tulnp | grep <port no>.

Reference: https://stackoverflow.com/questions/37916941/cant-connect-to-remote-mysql-server-10061, https://stackoverflow.com/questions/1673530/error-2003-hy000-cant-connect-to-mysql-server-on-127-0-0-1-111

To allow remote access to MySQL, you have to comment out bind-address and skip-networking in the configuration file.

This file is either at /etc/mysql/my.cnf or /etc/mysql/mysql.conf.d/mysqld.cnf.

If you cannot find bind-address in the my.cnf file, look for it in /etc/mysql/mysql.conf.d/mysqld.cnf file.

Next, you have to make sure the user is allowed remote access. Check your user with this:

SELECT User, Host FROM mysql.user;

If your user here has ‘127.0.0.1’ or ‘localhost’ listed as host, you don’t have remote access.

Change this with:

UPDATE mysql.user SET HOST='%' WHERE User='__here_your_username';

Flush privileges:

FLUSH PRIVILEGES;

The ‘%’ is a wildcard for ‘all hosts’.

You can then test your connection with MySQL Workbench, with your external IP address.

Setting up subdomains

Update Host DNS to route subdomain to correct IP address.

Reference: https://serverfault.com/questions/195611/how-do-i-redirect-subdomains-to-a-different-port-on-the-same-server

Run the following line on terminal (specify your domain and sub domain name correctly)

sudo nano /etc/apache2/sites-available/<subdomain.domain.com.conf>

Paste the following code and change as your requirement

<VirtualHost *:80>
    ServerAdmin me@mydomain.com
    ServerName dev.mydomain.com
    ProxyPreserveHost On

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    </Proxy>
    ProxyPass / http://localhost:8888/
    ProxyPassReverse / http://localhost:8888/
</VirtualHost>

Run the following lines on terminal (specify your domain and sub domain name correctly)

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2ensite subdomain.domain.com.conf
sudo service apache2 restart

If sudo a2enmod subdomain.domain.com.conf doesn’t work, and you get a module not found error, run the following code:

sudo a2dissite 000-default.conf //disables the default web site, allowing you to promote another one in its place.

Source: https://ubuntuforums.org/showthread.php?t=2100563

Further work

I intend to try this with a Raspberry Pi 3 in the near future.

Introduction to Unity3D

I originally wrote this on my site, https://blog.crazy.technology, which I will be taking down in a few days.

Unity3d Basics

Aims to provide the reader with a brief guide to coding with Unity.

Unity Editor

Common Terms

  • Editor – The Unity IDE
  • Scene – A collection of objects and scripts that are loaded and active together (like an Activity in Android)
  • GameObject – Any object/item seen in the hierarchy tab
  • Prefab – A GameObject (could have child GameObjects attached) with customized components/scripts attached. Common uses:
    • Instantiate a prefab via script (Instantiate(prefab, parentTransform))
    • Click and drag more copies of the prefab onto the scene, with different parameters
  • Component – Anything that is attached to a GameObject. Components give GameObjects their position, behavior, and other attributes. A script attached to a GameObject is also a component.

Tabs

There are 6 main tabs in the editor most commonly used. They are:

  • Hierarchy
    • Displays currently active scenes in the scene tab. (Recommendation: Unload/Remove scenes not currently in use)
    • Shows GameObjects that are in the scene, and their relative hierarchy (parent-child relationship)
  • Project
    • Shows all files in the Assets folder of the project
    • Unity creates multiple folders for each project, but the programmer only needs to access the Assets folder
  • Inspector
    • Shows the components/scripts that have been added to the currently selected GameObject
    • Each component/script has variables that can be adjusted. The adjustments can be performed here.
    • Note: If a script specifies a default value, and the value is changed in the inspector, the changes will take priority. These values are stored in the corresponding .meta file.
  • Console
    • Shows warnings, errors, and other Debug.Log() or print() messages
  • Scene
    • Shows GameObjects currently in the scene. They can be dragged and dropped, or their positions can be modified in the Inspector
  • Game
    • Shows the game view, via the currently active camera

Scripting in C#

Scripts are attached to GameObjects to give them certain attributes and behaviours.

They can also manipulate other GameObjects, by providing the script with a reference. This is most easily achieved by declaring a public variable, and assigning it in the Inspector via click-&-drag from the Hierarchy tab. In the example below, an InputField is assigned to the userName and pwd fields.

Variables declared without an access modifier are implicitly private, while those declared internal are available throughout the scripts with the same namespace, but are not exposed for modification in the inspector. If no namespace is referenced, the script will be available throughout the project.

Variables declared static are shared across all instances of the script. Only public, non-static variables will be available in the inspector for modification.

pic jere

Commonly Used in Scripting

  • gameObject: Reserved variable name, refers to the GameObject the script is attached to. Same with transform, etc…
  • gameObject.GetComponent<XXXX>(): Gets a component (XXXX) attached to the GameObject. GetComponent<XXXX> can be used with transform, camera. Can be chained, eg. gameObject.GetComponent<XXXX>().XXXX_Method()

Import & Export – Unity Packages (.unitypackages)

Often, a project will have components that can be re-used in other projects, or an entire project is meant to be included in the final application.

In this case, a Unity package (.unitypackage) is a way to easily export and import a project.

Importing

To import a package, select Assets > Import Package > Custom Package.

If you updated a package imported previously, when you perform this step, Unity will automatically detect the files that need to be updated. In either case, you will be allowed to select the files to import.

Exporting

To export a package, select Assets > Export Package. You will be allowed to select the files to export.

Common Problems

Application freezes when you press play (Editor)
Occasionally, an infinite loop in the Start() method will cause the application to freeze.
More commonly, an exception was thrown at startup. This may cause the application to freeze for some time (up to 5mins). If it does not appear to be “Not Responding” in the task manager, waiting for the application to resume will allow you to identify the exception being thrown via the Console.

Application crashes on start (mobile device)

The application works fine in the Editor, but crashes on start when deployed. This problem is tricky. You will need to connect your device to your PC, and check the Android log output, either via Android Studio or the Android Device Monitor.

Application freezes after loading successfully (mobile device)

The application freezes on/immediately after showing the first screen. This is most likely due to an unsuccessful network connection attempt on the main thread, which causes the application to freeze until connection is successful, or the connection attempt times out. Implementing network connections on a separate thread will resolve this issue.

Recommended Intro Tutorial

Unity’s Roll-A-Ball tutorial

In loving memory of Lucy, Singapore Zoo’s beloved giraffe

RIP Lucy, Singapore’s beloved female giraffe.

She died on Tuesday (5 Feb) after suffering a heart attack during a procedure to extract her foetus  😥 Lucy had been in labour for more than 48 hours and was unable to deliver her baby. Post by Wildlife Reserves Singapore (WRS):

It is with great sadness that we bring the devastating news that we have lost Lucy, our beloved giraffe. During the…

Posted by Wildlife Reserves Singapore on Tuesday, February 5, 2019

“Based on the time and consulting with other giraffe experts, our vets knew that the chances of survival for the calf were near zero,”

Wildlife Reserves Singapore

Due to the increased risk of complications should the dead calf fail to be expelled, the decision was made to extract the foetus and save Lucy. It was during this procedure that she went into cardiac arrest, and numerous attempts to revive her did not succeed.

Many had fond memories of Lucy, and offered condolences in the comments:

Of course, because this is the Internet, there will always be “medical experts” and nitpickers:

WRS first announced her pregnancy in October last year to much excitement, but alas, it was not meant to be. Our condolences go to the WRS team, who have put in so much love and effort to make the pregnancy go smoothly.

Lunar New Year is a pain in the a**!

Lunar New Year is exhausting. The first 2 days, 初一 and 初二, are gazetted public holidays in Singapore, but more often than not, I find myself preferring to be chilling at home by myself, or back in the office.

Things I appreciate about CNY

Ang baos are always great, no matter the amount. Having to distribute them, I feel the pinch, but having collected a great many of these over the years, it’s time to give back.

Catching up with that favourite aunt/uncle or cousin is excellent. You get the chance to catch up, find out if they’re alright, and wish them well (at least until the next year, when you get to see them again). Some might make your favourite food, or offer you nice words that don’t involving pressuring you to make drastic life decisions. But…

Stuff that grinds my gears

Having to travel around our sunny island country (emphasis sunny) takes a toll on you, it really does. Bloody hell, today was hot. It’s always hot this time of year.

Meeting the extended family is always awkward. We only meet once a year, so its like putting a bunch of strangers in the room and asking them to behave like a family for the duration of 3 hours. There will be that aunt that’s showing off their son’s accomplishments, and the other one that’s trying to give you health advice.

So you’ve spent half a day doing your hair? Another few days shopping for the perfect dress? Spent 2 hours in the morning doing your makeup? Guess what, you’ll have an aunt that goes, “Eh, you gained weight already ah?”

“Yes auntie, thank you for not noticing everything else.”

“Eh, you gained weight already ah?”

Also, the questions directed to your married but childless cousins / siblings, “when are you going to have a kid?”

“Auntie, children don’t go on trees”.

“Auntie, children don’t go on trees”

Forcing conversations with people you aren’t too familiar with is difficult, more so an introvert like me, so I shy away from the challenge as often as I can. This is not a problem in daily life, but at CNY gatherings, escape is not an option. So things get awkward, people start staring into space, and I try to sink deep into the ground.

It’s at times like these that I’m amazed at how much some people enjoy talking. As a listener, it’s exhausting (sorry). I know so-and-so are doing great, and how they can’t come this year to the gathering, but really, there should be a limit to how much one can talk.

All in all, CNY is a celebration I could do without. It is exhausting, and I find myself wishing I’m a million miles away. My obligation to my parents are the only reason I attend.

What about you? Do you enjoy Lunar New Year celebrations?

According to CNA, singles should move out

Out of your parents’ homes. On the first day of the Lunar New Year, no less. Citing studies conducted in the UK, the article lists the young person’s need for independence, increased costs of supporting more people, and the difficulties of splitting the household expenses between them, it hints that one should move out and live on their own.

Difficulties are bound to arise when related adults live together, and to some extent pool their economic resources, while still living largely separate lives. This creates economic relationships full of ambiguities, as parents desire to do the best for their sons and daughters, without having the same control over how their children live as they did when they were dependent.

Additionally, the article also mentions “they (parents) might have to maintain high rates of private rent or be unable to downsize to ease the transition to retirement”.

My first thought was, WTF is CNA talking about? After all, we are not at liberty to own property as singles until we are 35. Unless HDB changes their stance anytime soon, only the rich singles can afford to buy private property and move out.

These guys agree with me:

Additionally, the article asserts that tensions arose in discussions about how much young adults should contribute to household costs with their parents. Both young adults and parents who participated in the study agreed that while parents would pay most household bills, they should receive a regular “board” payment from the young adult. There was, however, difficulty in establishing a fair price.

However, as you read on, the article concludes with the reminder to parents that they may need to stay firm, and negotiate a fair contribution towards the costs of keeping a room available for their sons and daughters to live in.

Yet our research shows just how hard that is for parents, who will never see a son or daughter as a paying lodger, but always as part of the family. 

On a similar note, children who stay with their parents should remember that as independent adults, one should contribute to the household expenses and be mindful not to overburden ones parents.

Corruption Perception Index 2018 – Singapore places third

Transparency International, the think-tank behind the Corruption Perception Index (CPI), has published their 2018 version of the index. According to the CPI, Denmark is first among the least corrupted countries in the world with a CPI of 88, New Zealand second with 87, and then Singapore, Finland, Sweden and Switzerland third with 85.

Source: https://www.transparency.org/news/feature/cpi_2018_global_analysis

As a “flawed democracy” (their words, not mine), we are an outlier in that category. The CPI emphasizes how the systemic failure of countries to control corruption contributes to the worldwide crisis of democracy. No “Full Democracy” scores below 50 while very few autocratic states score above it.

What does this mean?

From the data, Transparency International concludes what we already know, that a healthy democracy is key to fighting public sector corruption.

Our research makes a clear link between having a healthy democracy and successfully fighting public sector corruption. Corruption is much more likely to flourish where democratic foundations are weak and, as we have seen in many countries, where undemocratic and populist politicians can use it to their advantage.

Delia Ferreira Rubio, chair of Transparency International 

From the map, the distribution of higher scoring countries are concentrated in the West, which makes Singapore an outlier. We do have a somewhat healthy democracy, I guess?

(Apart from unilaterally declaring a reserved Presidental Election, raising the CPF withdrawal age time and time again, auto opt-in to delay the CPF withdrawal age to 70, et cetera…)

How does Singapore fare compared to the nations around us?

One important factor Transparency International might have missed is that well-paid public servants is also key. 😉

In the picture above, you can see how our sunny island compares to our neighbours. We are a beacon of light in the region! A paragon of virtue! Or are we? Our politicians are paid far more than any other country’s leaders, so our system works, I guess?

This begs the question, how are other countries doing it?

Let us know what you think!

Death of local actor prompts fresh review of safety processes by the SAF

The Singapore Armed Forces (SAF) is establishing a new Inspector General’s Office (IGO), which will report directly to the Chief of Defense Force and have the full discretion to monitor and enforce safety processes and practices throughout the SAF.

The IGO was announced on 31 Jan at the Pasir Laba Camp by Chief of Defense Force Melvyn Ong at a meeting with 750 commanders, both active and ORNSmen.

The new office is one of a series of measures taken by the SAF following the death of actor Aloysius Pang on 23 January, four days after the operationally ready national serviceman was injured in a military exercise.

In a surprising move by the SAF, the army will also examine whether its exercises should be reduced and whether it will redesign and even remove selected courses, to lower the training tempo.

For example, certain confidence courses conducted in command schools will be removed.

It will also redesign its training to focus more on its objectives and increase its intensity, so that soldiers can better prepare and train effectively. Other moves include increasing the number of security inspection teams and full-time security officers to carry out checks and audits of unit-level security systems in the military, which will gradually lift an ongoing security timeout from 7 February.

A statement from the Ministry of Defense said that Lieutenant-General Ong called on all servicemen to adopt a “zero-accident “attitude in which they carry out daily tasks with alertness and caution in order to “do things right the first time, every time. ”

“Safety is the responsibility of command. The commanders answer for their men’s training and safety. To do this, commanders must be fully engaged and personally and closely involved in the training, operation and safety of their unit,” he said.

After the death of Corporal First Class (NS) Pang, SAF training security came under the spotlight–the fifth reported since September 2017, before which the SAF suffered four years of zero training and operational deaths.

Scoot flight to Singapore returns to Bangkok because of the unclaimed bag

Because of an unattended and unclaimed cabin bag, a Scoot flight from Bangkok to Singapore had to return to Thai capital on Wednesday. The budget airline stated in a statement that Flight TR607, which started at 11.55 a.m., returned to Suvarnabhumi Airport in Bangkok an hour after departure in the interests of security.

The plane landed at Suvarnabhumi Airport at approximately 2.10pm Bangkok time with 131 passengers on board. Scoot ‘s preliminary investigations found that the ground handling agent of the airline saw an unattended bag in the gatehold room and handed it to the cabin crew of the flight, believing that it belonged to one of the TR607 passengers.

The cabin crew accepted the bag despite not being able to determine the bag’s owner , “which was a violation of security protocols”.

“The captain was not informed of this problem until the flight departed from Bangkok, “said Scoot. After being informed of the situation, he decided to go back to Bangkok. Passengers landed at the airport from the aircraft and the security staff carried out the necessary checks, said the airline.

Scoot added that the bag was removed from the aircraft by airport authorities. Flight TR607 later left Bangkok at the local time of 7.49pm. Scoot said that passengers missing their connecting flights in Singapore were transferred to the next available flights by Scoot or partner airlines, including Singapore Airlines and SilkAir.

“We apologize sincerely for the delay and we will review our training processes to prevent recurrence, “said Scoot.

With the recent spike in travel disruptions that involved Scoot, would you think twice before travelling with them?

National HIV Registry leak: Let’s talk about HIV

Former head of the National Public Health Unit (NPHU), Singaporean doctor Ler Teck Siang, is in a lot of trouble with the authorities here. He currently faces a number of drug-related charges, as well as
charges under the Official Secrets Act (OSA).

He allegedly failed to “take reasonable care” of the data by “failing to retain possession” of a thumbdrive containing the confidential data of more than 14,000 HIV patients. He had obtained said data from the National HIV Registry.

A Singaporean doctor at the centre of the HIV information leak is also facing three drug-related charges, including methamphetamine trafficking.

TNP, 1 Feb 2019

Why have a National HIV Registry?

HIV/AIDS is a global pandemic. As of 2016 , approximately 36.7 million people have HIV worldwide with the number of new infections that year being about 1.8 million. This is down from 3.1 million new infections in 2001. Slightly over half the infected population are women and 2.1 million are children. (Source: Wikipedia)

It is therefore important to keep a record of individuals with HIV in order to understand and contain the spread of the virus within our population. The data enables the authorities to take preventive measures when warranted.

What should you do if you come into possession of the leaked registry data?

Report it to the relevant authorities, and ignore it. Basic decency dictates you not share this information on Facebook (duh!).

Common misconceptions about HIV

The risk of transmission is higher in homosexuals

Globally, the most common mode of HIV transmission is via sexual contacts between people of the opposite sex

Why this misconception?

As of 2014, most HIV transmission in the United States occurred among men who had sex with men (83% of new HIV diagnoses among males aged 13 and older and 67% of total new diagnoses)

The chances of male to female transmission is higher

This is true to some extent, in the context of high-income countries

Male to FemaleFemale to Male
High-income countries0.08%0.04%
Low-income countries0.30%0.38%

Rough sex, and anal sex, further increase the risk of transmission.

Skin contact can transmit HIV

This is untrue, and should be common knowledge in 2019. There is the risk of transmission if there’s breakage in the skin and exchange of bodily fluids, but the chances are very low.

Should the Government discriminate against HIV-positive foreigners coming here to work?

In April 2015, the ban against HIV-positive foreigners travelling to Singapore was lifted, reflecting changes in immigration policies in other first-world countries. However, they are still not allowed to work here.

MOH asserts that “… the public health risk posed by long-stayers is not insignificant, hence the restriction on long-term visits has been retained.” (ST, Aug 2015)

Some would say that this is unnecessarily discriminatory. What do you think?

Honestbee Stops Buzzing, Bees Abandoned

Honestbees “shopper bees” were abruptly informed yesterday (30 Jan) that it had “temporarily paused” its partnership with FairPrice. FairPrice said the decision is due to a “review of the existing operations and collaboration process”.

“For us shoppers, we started hearing this news from NTUC (FairPrice) since last night, but only received an email (from honestbee at) around 1pm, telling us that all shopper positions will no longer be available,”
a shopper who spoke to ChannelNewsAsia shared.

Many of our bees, although (they) are part-timers with us, have been a critical part of our family who have played a key role in our success”

Honestbee spokesperson

Although shoppers are freelancers, Honestbee acknowledged their contribution to the company’s growth, and further invited them to take on roles at the company’s new grocery store last October called habitat by honestbee.

Were you affected by the sudden cessation of this partnership?