Ubuntu – Running PHP-CLI server

PHPserverservices

Good day everyone,

I recently got interested in the WebSocket technology. I built myself a server using PHP which I ran on Windows using the PHP CLI. That was fine for development, but now I need to think about deployment.

I got myself a little VPS running Ubuntu Server 10.10. I have basic knowledge of Linux, so I set up my SSH client, installed PHP-CLI and messed around to make sure it works, which it does.

Now, I can simply run my server using

php server.php

But I don't think that's a great way of doing it. A few concerns:

  • What will happen to the console output once I close my SSH client?
  • What if the server crashes?
  • I can't do anything else on my VPS while the server is running this way in the main thread

Regarding the console output; is there a way to redirect STDOUT or something to a file, so I can still see the console output on Windows but on my VPS it is logged instead? As for the server crashes, what are some good ways to restart some processes automatically on server boot? And I think I could run it as a daemon or a service or something like that so it doesn't hang the main thread?

So, what are some usually used solutions for those problems? Is there somewhere I can read up more on this? I'd like to learn a little bit in the process!

Thanks.

Best Answer

To redirect both output and any errors to some_other_file:

php server.php 2>&1 some_other_file

The >& redirects a stream to another file descriptor (in BASH shell):

  • 0 is stdin
  • 1 is stdout
  • 2 is stderr

Or, 2>&1 redirects 2 to 1. And then to watch that output in real time:

tail -f some_other_file

Starting at boot time: you could call the script from /etc/rc.local. Or, a more advanced solution might be to write a script in the /etc/init.d/ directory. See /etc/init.d/README for how to do that.

If you make the PHP file, server.php, executable, you can add a line to the top of the file (aka file magic/shebang/hashbang) to call it this way: server.php instead of php server.php. You could even remove the php extension if for some reason you want to do that. Like this:

#!/usr/bin/php
<?php
    // PHP code here

Upstart is probably the way to go to make sure the service stays running. This method does not involve /etc/rc*. Upstart has five packages, all installed by default:

  • Upstart init daemon and initctl utility
  • upstart-logd provides the logd daemon and job definition file for logd service
  • upstart-compat-sysv provides job definition files for the rc tasks and the reboot, runlevel, shutdown, and telinit tools that provide compatibility with SysVinit
  • startup-tasks provides job definition files for system startup tasks
  • system-services provides job definition files for tty services

The learning is very enjoyable and well worth it. Upstart has a website: http://upstart.ubuntu.com/

Other good posts: What's the difference between "Service" and "/etc/init.d/"?