[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Osaka/Yokohama/Tokushima] Looking for infrastructure/server side engineers!

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Deployed by over 500 companies] AWS construction, operation, maintenance, and monitoring services

[Successor to CentOS] AlmaLinux OS server construction/migration service

[Successor to CentOS] AlmaLinux OS server construction/migration service

[For WordPress only] Cloud server “Web Speed”

[For WordPress only] Cloud server “Web Speed”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Cheap] Website security automatic diagnosis “Quick Scanner”

[Reservation system development] EDISONE customization development service

[Reservation system development] EDISONE customization development service

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Registration of 100 URLs is 0 yen] Website monitoring service “Appmill”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[Compatible with over 200 countries] Global eSIM “Beyond SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[If you are traveling, business trip, or stationed in China] Chinese SIM service “Choco SIM”

[Global exclusive service] Beyond's MSP in North America and China

[Global exclusive service] Beyond's MSP in North America and China

[YouTube] Beyond official channel “Biyomaru Channel”

[YouTube] Beyond official channel “Biyomaru Channel”

Hello World from PHP on Google App Engine

Hello.
I'm Mandai, in charge of Wild on the development team.

Google App Engine (hereinafter referred to as GAE) is a powerful Paas, but there are many things you cannot proceed without knowing something before getting started.

For example, how to write app.yaml, what functions can be used, whether frameworks can be used in the first place, and what the URL should be.
Moreover, the development speed of the SDK and gcloud commands is fast, and I sometimes feel like giving up because I can't deploy using the command I researched.

So, based on the latest GAE environment at the moment (2017/03/22), I will try deploying a Hello World-like program and get a feel for the flow.

Due to space constraints, I will proceed with the discussion assuming that the latest gcloud command is installed.

 

Creating app.yaml

Create an appropriate directory and create app.yaml.

app.yaml is a configuration file that configures the program's environment.

In app.yaml, we will first include the execution environment.

# app.yaml # Required field runtime: php55

We selected PHP5.5 as the execution environment.
Or rather, it seems that GAE has no other choice than PHP5.5.

 

write the source

This time, it's Hello World, but there's no trick to just saying "echo "hello world";, so I'm going to create a simple program that uses Google SQL.

Let's create a file named form.php.
I prepared the following sources.

<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = getenv('MYSQL_USER'); $password = getenv('MYSQL_PASSWORD'); $dsn = getenv('MYSQL_DSN'); $subject = isset($_POST['subject']) ? $_POST['subject'] : null; $content = isset($_POST['content']) ? $_POST['content'] : null; if (!empty($dsn) && !empty($username) && !empty($password) && !is_null($subject) && !is_null($content)) { $db = new PDO($dsn, $username, $password); $stmt = $db-> prepare('INSERT INTO `forms` (`subject`, `content`, `created_at`) VALUES (?, ?, ?)'); $data = array( $subject, $content, date('Ymd H:i :s'), ); if (!$stmt->execute($data)) { $info = array( 'title' => $stmt->errorCode(), 'body' => $stmt->errorInfo( ), ); } else { $info = array( 'title' => 'info', 'body' => 'Registered!', ); } } }?><!doctype html><html><head><title> test form </title><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></head><body><div class="container"><?php if (isset($info)){?><div class="panel panel-default alert alert-info"><div class="panel-heading"><?php echo $info['title'] ?></div><div class="panel-body"><?php echo $info['body'] ?></div></div><?php } ?><form method="POST"><div class="form-group"> <label for="subject">title</label><input id="subject" type="text" class="form-control" name="subject"></div><div class="form-group"> <label for="content">Main text</label><textarea id="content" class="form-control" name="content" rows="10"></textarea></div> <button class="btn btn-default">send</button></form></div></body></html>

This is a simple registration form page using Twitter Bootstrap.

The following DB tables were used in this program.

CREATE TABLE `forms` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `subject` varchar(255) DEFAULT NULL, `content` text, `created_at` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE= InnoDB DEFAULT CHARSET=utf8;

Since we will be using Google Cloud SQL, we will need login information for Google Cloud SQL, so if you want to use a user other than root, create one in advance.
Of course, there is no problem with the operation if you write it directly in the source code, but since there is also a configuration file called app.yaml, I will try writing it there.

# app.yaml # Add to app.yaml created earlier env_variables: MYSQL_DSN: mysql:unix_socket=/cloudsql/[instance connection name];dbname=[DB schema name to be used] MYSQL_USER: [MySQL login user] MYSQL_PASSWORD : [MySQL login password] # Also add URL routing handlers: - url: /test script: form.php secure: always

You can register constants in the env_variables item just like defining it.
To receive this value on the PHP side, use the getenv() function (it is not actually defined).

I also secretly added an item called handlers, but without it the URL won't be recognized, so I'll create a URL called /test.
The secure item is related to the use of HTTPS and has the following options.

always

Use only HTTPS (access via HTTP will redirect)

optional

Accessible via both HTTP/HTTPS

never

Accessible only via HTTP

 

Check operation in local environment

Writing the source code and checking its operation on GAE is a hassle, and it is difficult to do so once the operation has started, so a method to test it in a local environment is also provided.

If you run the python script dev_appserver.py included in the gcloud SDK, you can start up the local server and check its operation, but it seems that you cannot connect to Cloud SQL properly as is.
However, if you use cloud_sql_proxy described later, you can connect to the DB without thinking about anything.

dev_appserver.py is included in the Google Cloud SDK, and is executed by specifying the path (relative path is acceptable) of the directory where app.yaml is located as an argument.

In the case of Windows, it is installed in a fairly deep directory, so I think one way is to pass the path to the directory where the Google Cloud SDK executable file is located.

 

Connect to Google Cloud SQL from your local development environment using cloud_sql_proxy

You cannot connect to Cloud SQL from the local environment using the same app.yaml as the production version, but if you use a separate tool called cloud_sql_proxy, you can easily test an application using Cloud SQL even locally.
I'll briefly summarize the steps.

  1. Using Google Cloud SQL , get cloud_sql_proxy and rename the file name.
  2. Move to the location specified by the path (for example, the Google Cloud SDK directory).
  3. Run gcloud auth application-default login
  4. The OAuth authentication page will be displayed in your browser, so select the login user and authorize it.
  5. [For Windows] cloud_sql_proxy.exe -instances=[instance connection name]=tcp:3306

I think the commands may change slightly in a situation where multiple users are used (mainly around the gcloud auth command), but I can't say anything because it hasn't been tested.
By using this tool, there is no need to register the connection source IP address in Cloud SQL, so once the settings are completed, development becomes much easier.

 

deploy

A gcloud command is provided for deploying to GAE, so run the following command in the directory where app.yaml is located.

gcloud app deploy

If it has already been deployed, you will be asked to confirm, but I think you can generally deploy it without any problems.

Also, at this time, if handlers that are not routed are registered in app.yaml, a warning like the one below will be displayed.

WARNING: The URL path "/hogehoge" is reserved and will not be matched.

In this case, if you deploy as is, the URL for running the program will not be set, so make adjustments.

 

View access log

Although there is a slight time lag, access logs can be checked from the local environment using the gcloud command.

gcloud app logs tail -s default

As shown above, the accessed path and response code are displayed, so a simple error check is possible.

 

View error log

Since GAE is Paas, it is not possible to log in to the server and check the error log.

Therefore, after deploying, to check for errors, check the logs using Stackdriver Error Reporting

It's easy to see because it displays things that are neatly parsed, but the information is spread out all over the place, so it's hard to get used to it.

 

summary

It's a bit different from my usual development process, so I'm often confused, but I feel like if I take it one step at a time, things will work out.
In particular, I found the ability to connect to Google Cloud SQL locally via a proxy to be very easy to use.

It's a perfect service for hosting small useful tools, and even when the scale grows, it automatically increases instances, so it can be used for a variety of purposes.
In addition, you can use memcache, and a directory for the application is created in Google Cloud Storage, which is designed to be easily handled, so you don't have to worry about where to store various data.

That's it.

If you found this article helpful , please give it a like!
0
Loading...
0 votes, average: 0.00 / 10
1,102
X facebook Hatena Bookmark pocket
[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

[2025.6.30 Amazon Linux 2 support ended] Amazon Linux server migration solution

The person who wrote this article

About the author

Yoichi Bandai

My main job is developing web APIs for social games, but I'm also fortunate to be able to do a lot of other work, including marketing.
Furthermore, my portrait rights in Beyond are treated as CC0 by him.