iEFdev

Code, Computers & Random Junk

My Server Setup in OS X - Part 4: FastCGI and Virtualhost

This continues part 3, talking about my server setup in OS X. As before… This is not a tutorial or a HowTo …more of a conceptual overview. You might want/have to fill in the missing parts your self.


In this part I’ll try to explain my setup - how I use it. Some parts have already been mentioned in part 2, so refer to that one as well. I’m just trying to tie it together here. :)


The post might seem to be a bit lengthy, but a lot of that is because of the examples files, which I’ve posted the full versions of, with all the default comments. I was (eventually) going for a fifth “Sumup” post, but this is the last one now.

PHP Module

My PHP 5.4 version is running as mod_php. So, first it has to be enabled in httpd.conf (read in part 2). After all the “LoadModule” I have this:

# PHP module
LoadModule php5_module                  /usr/lib/httpd/modules/libphp5.so

# GeoIP
LoadModule geoip_module                 /usr/lib/httpd/modules/mod_geoip.so

# FastCGI (mod_fastcgi)
LoadModule fastcgi_module               /usr/lib/httpd/modules/mod_fastcgi.so

# Turn off SuExec and FastCgiWrapper
Suexec Off
FastCgiWrapper Off

Loading the PHP module, and also the GeoIP and FastCGI. Since we are not using “Suexec” we set that one + the wrapper to Off.

A bit down in the file you see:

# PHP54
# ======================================================
# Since we use 2 versions of php (5.{4,6}) We load this
# file withing the virtualhost 
#
<IfModule php5_module>
  #Include conf/other/php5.conf
</IfModule>

It’s commented out. I should actually remove that part to make it cleaner, but it’s there. What it means is that instead of loading the php5.conf file from here (as would be a normal thing to do), we call it later from the virtualhost.

So in the end of all Include’s there is this part:

# Include Macros
Include conf/other/httpd-macros.conf

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

# Enabled vHosts...
IncludeOptional conf/sites-enabled/*.conf

# Virtual host for Sites/Users
IncludeOptional conf/users/*.conf

# Undefine Macros
UndefMacro NoExt
UndefMacro FastPHP
UndefMacro ModPHP
UndefMacro AddFastExt
UndefMacro AddPhpExt
UndefMacro to443

Loading the macro’s, so they can be used in the httpd-vhosts-conf + any other vhost files. Then, a good practice is to undefine the macros - which is done there in the end.

The Macro used for mod_php loks like:

<Macro ModPHP>
    Include conf/other/php5.conf
</Macro>

….and in that file:

1
2
3
4
5
6
7
8
# PHP module (5.4)
<IfModule php5_module>
  AddType application/x-httpd-php .php
  AddType application/x-httpd-php-source .phps
  <IfModule dir_module>
      DirectoryIndex index.php index.html
  </IfModule>
</IfModule>

In a Virtualhost you call it with Use ModPHP. That is all. :)

FPM/FastCGI

This one takes a lot more configuration and editing …and there may be som trial and error process to it. But it’s worth the time learning/editing until it works. It’s so much better.

First. Using 2 version and one with FPM/FastCGI… Don’t use MPM “Prefork”. Instead use “Worker” or “Event”. I use Event. Depending on your hardware and usage you might want to use different settings. This is what I have at the moment. I only use this server for testing/development…

# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestWorkers: maximum number of worker threads
# MaxConnectionsPerChild: maximum number of connections a server process serves
#
<IfModule mpm_event_module>
    StartServers           4
    MinSpareThreads       25
    MaxSpareThreads      150
    ThreadLimit           25
    ThreadsPerChild       10
    MaxRequestWorkers    150
    MaxRequestsPerChild    0
</IfModule>

Next is to look at the /etc/php56/fpm/php-fpm.conf. The [global] configuration.

This is my file…

php-fpm.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
;;;;;;;;;;;;;;;;;;;;;
; FPM Configuration ;
;;;;;;;;;;;;;;;;;;;;;

; All relative paths in this configuration file are relative to PHP's install
; prefix (/usr/local/php56). This prefix can be dynamically changed by using the
; '-p' argument from the command line.

; Include one or more files. If glob(3) exists, it is used to include a bunch of
; files from a glob(3) pattern. This directive can be used everywhere in the
; file.
; Relative path can also be used. They will be prefixed by:
;  - the global prefix if it's been set (-p argument)
;  - /usr/local/php56 otherwise
;include=/etc/php56/fpm/pool.d/*.conf


;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]
; Pid file
; Note: the default prefix is /var/php56
; Default Value: none
pid = run/php-fpm.pid

; Error log file
; If it's set to "syslog", log is sent to syslogd instead of being written
; in a local file.
; Note: the default prefix is /var/php56
; Default Value: log/php-fpm.log
error_log = /var/php56/log/php-fpm.log

; syslog_facility is used to specify what type of program is logging the
; message. This lets syslogd specify that messages from different facilities
; will be handled differently.
; See syslog(3) for possible values (ex daemon equiv LOG_DAEMON)
; Default Value: daemon
;syslog.facility = daemon

; syslog_ident is prepended to every message. If you have multiple FPM
; instances running on the same server, you can change the default value
; which must suit common needs.
; Default Value: php-fpm
;syslog.ident = php-fpm

; Log level
; Possible Values: alert, error, warning, notice, debug
; Default Value: notice
log_level = notice
;log_level = debug

; If this number of child processes exit with SIGSEGV or SIGBUS within the time
; interval set by emergency_restart_interval then FPM will restart. A value
; of '0' means 'Off'.
; Default Value: 0
;emergency_restart_threshold = 0

; Interval of time used by emergency_restart_interval to determine when 
; a graceful restart will be initiated.  This can be useful to work around
; accidental corruptions in an accelerator's shared memory.
; Available Units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;emergency_restart_interval = 0

; Time limit for child processes to wait for a reaction on signals from master.
; Available units: s(econds), m(inutes), h(ours), or d(ays)
; Default Unit: seconds
; Default Value: 0
;process_control_timeout = 0

; The maximum number of processes FPM will fork. This has been design to control
; the global number of processes when using dynamic PM within a lot of pools.
; Use it with caution.
; Note: A value of 0 indicates no limit
; Default Value: 0
; process.max = 128

; Specify the nice(2) priority to apply to the master process (only if set)
; The value can vary from -19 (highest priority) to 20 (lower priority)
; Note: - It will only work if the FPM master process is launched as root
;       - The pool process will inherit the master process priority
;         unless it specified otherwise
; Default Value: no set
; process.priority = -19

; Send FPM to background. Set to 'no' to keep FPM in foreground for debugging.
; Default Value: yes
daemonize = no

; Set open file descriptor rlimit for the master process.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit for the master process.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Specify the event mechanism FPM will use. The following is available:
; - select     (any POSIX os)
; - poll       (any POSIX os)
; - epoll      (linux >= 2.5.44)
; - kqueue     (FreeBSD >= 4.1, OpenBSD >= 2.9, NetBSD >= 2.0)
; - /dev/poll  (Solaris >= 7)
; - port       (Solaris >= 10)
; Default Value: not set (auto detection)
;events.mechanism = epoll

; When FPM is build with systemd integration, specify the interval,
; in second, between health report notification to systemd.
; Set to 0 to disable.
; Available Units: s(econds), m(inutes), h(ours)
; Default Unit: seconds
; Default value: 10
;systemd_interval = 10


;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ; 
;;;;;;;;;;;;;;;;;;;;

; Multiple pools of child processes may be started with different listening
; ports and different management options.  The name of the pool will be
; used in logs and stats. There is no limitation on the number of pools which
; FPM can handle. Your system will tell you anyway :)

; To configure the pools it is recommended to have one .conf file per
; pool in the following directory:
;
; Pools are store in pool.d-available/, and symlinked to pool.d/
; Just like like the virtual hosts
;
; www.conf is in pool.d/ by default to supress errors from empty dir
include=/etc/php56/fpm/pool.d/*.conf 

Nothing special there, but the pid-/logfile. You may need to create those manually, and also set some permissions.

pid = run/php-fpm.pid
error_log = /var/php56/log/php-fpm.log

Set “owner:group” to _www. If not already created…

sudo mkdir -p /var/php56/{fpm.d,log,run,sessions}
sudo chown -R _www:_www /var/php56

While creating folders… Create the one in /srv/http as well.

sudo mkdir .php56-fpm
$ sudo chown _www:_www .php56-fpm

Then the pools, and the default pool. I have 2 folders like:

  • /etc/php56/fpm/pool.d
  • /etc/php56/fpm/pool.d-available

I don’t have a script to automate the activation though… I’m doing that manually. But the general idea is to have all in pool.d-available and symlink in to pool.d. Easy to (un)activate as you add or remove sites.

Here’s the pool I call 00-default.conf. It’s in pool.d without being symlink as it is the pool of the default page (/srv/http/public_html).

php-fpm.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ; 
;;;;;;;;;;;;;;;;;;;;
; www.conf :: tlp. ; 
;;;;;;;;;;;;;;;;;;;;

; Multiple pools of child processes may be started with different listening
; ports and different management options.  The name of the pool will be
; used in logs and stats. There is no limitation on the number of pools which
; FPM can handle. Your system will tell you anyway :)

; Start a new pool named 'www'.
; the variable $pool can we used in any directive and will be replaced by the
; pool name ('www' here)
[www]

; Per pool prefix
; It only applies on the following directives:
; - 'slowlog'
; - 'listen' (unixsocket)
; - 'chroot'
; - 'chdir'
; - 'php_values'
; - 'php_admin_values'
; When not set, the global prefix (or /usr/local/php56) applies instead.
; Note: This directive can also be relative to the global prefix.
; Default Value: none
;prefix = /srv/http

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = _www
group = _www

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
;listen = 127.0.0.1:9000
listen = /var/php56/fpm.d/00-default.sock


; Set listen(2) backlog.
; Default Value: 65535 (-1 on FreeBSD and OpenBSD)
;listen.backlog = 65535

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = _www
listen.group = _www
listen.mode = 0660

; List of ipv4 addresses of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
;listen.allowed_clients = 127.0.0.1

; Specify the nice(2) priority to apply to the pool processes (only if set)
; The value can vary from -19 (highest priority) to 20 (lower priority)
; Note: - It will only work if the FPM master process is launched as root
;       - The pool processes will inherit the master process priority
;         unless it specified otherwise
; Default Value: no set
; process.priority = -19

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives. With this process management, there will be
;             always at least 1 children.
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
;  ondemand - no children are created at startup. Children will be forked when
;             new requests will connect. The following parameter are used:
;             pm.max_children           - the maximum number of children that
;                                         can be alive at the same time.
;             pm.process_idle_timeout   - The number of seconds after which
;                                         an idle process will be killed.
; Note: This value is mandatory.
pm = ondemand

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 5

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 2

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 1

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 3

; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
;pm.process_idle_timeout = 10s;

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. It shows the following informations:
;   pool                 - the name of the pool;
;   process manager      - static, dynamic or ondemand;
;   start time           - the date and time FPM has started;
;   start since          - number of seconds since FPM has started;
;   accepted conn        - the number of request accepted by the pool;
;   listen queue         - the number of request in the queue of pending
;                          connections (see backlog in listen(2));
;   max listen queue     - the maximum number of requests in the queue
;                          of pending connections since FPM has started;
;   listen queue len     - the size of the socket queue of pending connections;
;   idle processes       - the number of idle processes;
;   active processes     - the number of active processes;
;   total processes      - the number of idle + active processes;
;   max active processes - the maximum number of active processes since FPM
;                          has started;
;   max children reached - number of times, the process limit has been reached,
;                          when pm tries to start more children (works only for
;                          pm 'dynamic' and 'ondemand');
; Value are updated in real time.
; Example output:
;   pool:                 www
;   process manager:      static
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          62636
;   accepted conn:        190460
;   listen queue:         0
;   max listen queue:     1
;   listen queue len:     42
;   idle processes:       4
;   active processes:     11
;   total processes:      15
;   max active processes: 12
;   max children reached: 0
;
; By default the status page output is formatted as text/plain. Passing either
; 'html', 'xml' or 'json' in the query string will return the corresponding
; output syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
;   http://www.foo.bar/status?xml
;
; By default the status page only outputs short status. Passing 'full' in the
; query string will also return status for each pool process.
; Example: 
;   http://www.foo.bar/status?full
;   http://www.foo.bar/status?json&full
;   http://www.foo.bar/status?html&full
;   http://www.foo.bar/status?xml&full
; The Full status returns for each process:
;   pid                  - the PID of the process;
;   state                - the state of the process (Idle, Running, ...);
;   start time           - the date and time the process has started;
;   start since          - the number of seconds since the process has started;
;   requests             - the number of requests the process has served;
;   request duration     - the duration in µs of the requests;
;   request method       - the request method (GET, POST, ...);
;   request URI          - the request URI with the query string;
;   content length       - the content length of the request (only with POST);
;   user                 - the user (PHP_AUTH_USER) (or '-' if not set);
;   script               - the main script called (or '-' if not set);
;   last request cpu     - the %cpu the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because CPU calculation is done when the request
;                          processing has terminated;
;   last request memory  - the max amount of memory the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because memory calculation is done when the request
;                          processing has terminated;
; If the process is in Idle state, then informations are related to the
; last request the process has served. Otherwise informations are related to
; the current request being served.
; Example output:
;   ************************
;   pid:                  31330
;   state:                Running
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          63087
;   requests:             12808
;   request duration:     1250261
;   request method:       GET
;   request URI:          /test_mem.php?N=10000
;   content length:       0
;   user:                 -
;   script:               /home/fat/web/docs/php/test_mem.php
;   last request cpu:     0.00
;   last request memory:  0
;
; Note: There is a real-time FPM status monitoring sample web page available
;       It's available in: /usr/share/php56/fpm/status.html
;
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set 
pm.status_path = /p56/status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
ping.path = /p56/ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
ping.response = pong

; The access log file
; Default: not set
;access.log = log/$pool.access.log
;access.log = log/00-default.access.log

; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request
;      it can accept the following format:
;      - %{user}C for user CPU only
;      - %{system}C for system CPU only
;      - %{total}C  for user + system CPU (default)
;  %d: time taken to serve the request
;      it can accept the following format:
;      - %{seconds}d (default)
;      - %{miliseconds}d
;      - %{mili}d
;      - %{microseconds}d
;      - %{micro}d
;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some exemples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
;  %f: script filename
;  %l: content-length of the request (for POST request only)
;  %m: request method
;  %M: peak of memory allocated by PHP
;      it can accept the following format:
;      - %{bytes}M (default)
;      - %{kilobytes}M
;      - %{kilo}M
;      - %{megabytes}M
;      - %{mega}M
;  %n: pool name
;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o
;      - ....
;  %p: PID of the child that serviced the request
;  %P: PID of the parent of the child that serviced the request
;  %q: the query string 
;  %Q: the '?' character if query string exists
;  %r: the request URI (without the query string, see %q and %Q)
;  %R: remote IP address
;  %s: status (response code)
;  %t: server time the request was received
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;  %T: time the log has been written (the request has finished)
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"

; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
slowlog = log/00-default.log.slow

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
; of its subdirectories. If the pool prefix is not set, the global prefix
; will be used instead.
; Note: chrooting is a great security feature and should be used whenever 
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot = 

; Chdir to this directory at the start.
; Note: relative path can be used.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Note: on highloaded environement, this can cause some delay in the page
; process time (several ms).
; Default Value: no
catch_workers_output = yes

; Clear environment in FPM workers
; Prevents arbitrary environment variables from reaching FPM worker processes
; by clearing the environment in workers before env vars specified in this
; pool configuration are added.
; Setting to "no" will make all environment variables available to PHP code
; via getenv(), $_ENV and $_SERVER.
; Default Value: yes
;clear_env = no

; Limits the extensions of the main script FPM will allow to parse. This can
; prevent configuration mistakes on the web server side. You should only limit
; FPM to .php extensions to prevent malicious users to use other extensions to
; exectute php code.
; Note: set an empty value to allow all extensions.
; Default Value: .php
;security.limit_extensions = .php .php3 .php4 .php5
security.limit_extensions = .php .srv

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'. 
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Note: path INI options can be relative and will be expanded with the prefix
; (pool, global or /usr/local/php56)

; Default Value: nothing is defined by default except the values in php.ini and
; specified at startup with the -d argument

;;; Mail
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i
php_admin_value[mail.log] = /srv/http/logs/00-default-php_mail_log

;;; Errors
php_flag[display_errors] = on
php_admin_value[error_log] = /srv/http/logs/00-default-php_errors_log
php_admin_flag[log_errors] = on

;;; Mem
;php_admin_value[memory_limit] = 128M
php_admin_value[memory_limit] = 32M

;; Session & Dirs
php_admin_value[session.gc_maxlifetime] = 3600
php_admin_value[session.save_path] = /srv/http/tmp
php_admin_value[upload_tmp_dir] = /srv/http/tmp

Some settings:

listen = /var/php56/fpm.d/00-default.sock

listen.owner = _www
listen.group = _www
listen.mode = 0660

pm = ondemand

You can play with the server settings etc, and you can see in the end where the files are going.


The default Vhost

In /etc/httpd/conf/extra/httpd-vhosts.conf I have the default site set up, and a “fallback” page (just in case), and also the old default OS X default page. Don’t know why, but I guess that when I set it up I needed to test the possibilities to mix and add different sites/pages whit the 2 different PHP versions. Anyway, I use mod_php on that one.

httpd-vhosts.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#
# Virtual Hosts :: Main file.
# Default Site + Fallback
#

#===============================================
# DocumentRoot /srv/http/public_html
#===============================================
<VirtualHost *:80>
  Define vhost_srv myhostname

  ServerName ${vhost_srv}
  ServerAlias www.${vhost_srv} localhost
  ServerAdmin admin@${vhost_srv}

    DocumentRoot /srv/http/public_html

  <IfModule alias_module>
      #Alias /pma /srv/www/_phpMyAdmin/public_html
      ScriptAlias /cgi-bin/ "/srv/www/${vhost_srv}/cgi-bin/"
  </IfModule>

  <Directory "/srv/http/public_html">
      Options -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
      Require host localhost
      Require ip ::1
#     Require all granted

      Use AddFastExt srv

      Use NoExt srv
      Use NoExt php
  </Directory>

  # Choose PHP Version
  # ==================
  Use FastPHP 00-default
  #Use ModPHP
</VirtualHost>


#===============================================
# DocumentRoot /srv/http/public_default
#===============================================
# No php just a static html page as a fallback
#

<VirtualHost *:80 *:81 *:443>
  ServerName foobar.dev
    DocumentRoot /srv/http/xfallback

  ErrorLog /srv/http/logs/xfallback-error_log
  CustomLog /srv/http/logs/xfallback-access_log combined

  <Directory "/srv/http/xfallback">
      Options -Indexes +FollowSymLinks
      Require host localhost
      Require ip 127
      Require ip ::1
#     Require all granted
  </Directory>
</VirtualHost>


#=== [xtra] ====================================
# OS X default: /Library/WebServer/Documents
#===============================================

<VirtualHost *:80>
  Define vhost_srv default.osx

  ServerName ${vhost_srv}
  ServerAlias www.${vhost_srv}
  ServerAdmin admin@${vhost_srv}

  ErrorLog /Library/WebServer/Logs/error_log
  CustomLog /Library/WebServer/Logs/access_log combined

  DocumentRoot /Library/WebServer/Documents

  <Directory "/Library/WebServer/Documents">
      Options -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
      Require host localhost
      Require ip 127
      Require ip ::1
#     Require all granted

      Use NoExt php
  </Directory>

  # Choose PHP Version
  # ==================
  #Use FastPHP ${vhost_srv}
  Use ModPHP
</VirtualHost>

This one has a little bit of mix with macros and manual settings.

The first one, using FastCGI. All I do here is defining the vhost_srv.

Define vhost_srv myhostname

Then I can use $vhost_srv throughout the virtualhost. In the end it says: Use FastPHP 00-default.

So, looking at the Macro for that… (/etc/httpd/conf/other/httpd-macros.conf)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# === PHP56 :: FPM/FastCGI =====================================
# === pool: [$sockname] (eg [foobar.dev])
<Macro FastPHP $sockname>
  <IfModule fastcgi_module>
      AddType application/x-httpd-php56 .php
      Action application/x-httpd-php56 /.php-fpm

      <IfModule alias_module>
          Alias /.php-fpm /srv/http/.php56-fpm/$sockname
      </IfModule>
      FastCGIExternalServer /srv/http/.php56-fpm/$sockname -socket /var/php56/fpm.d/$sockname.sock

      # Sock folder
      <LocationMatch "^\/?\.php\-fpm">
          Require all denied
          Require env REDIRECT_STATUS
      </LocationMatch>
      <Directory /srv/http/.php56-fpm>
          Require all denied
          Require env REDIRECT_STATUS
          <Files "$sockname">
              Require all denied
          </Files>
      </Directory>
  </IfModule>
</Macro>

AddType and Action is first use to set up php and telling it where the socket are - which is an alias. Then using the socket in /var/php56 ... etc.

There’s a location mactch on the socket folder: /srv/http/.php56-fpm and it’s restricted. A Directory tag for the same folder is also used, and the socket is denied.

Now, with these settings and if your folders are correct, with proper permissions - it should kick alive now.


The other Macros used are

    Use AddFastExt srv

    Use NoExt srv
    Use NoExt php

“AddFastExt” adds .srv as a php extension and “NoExt” makes it work without. like visiting “info” instead of “info.php”

The Macros are:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<Macro AddFastExt $ext>
  AddType application/x-httpd-php56 $ext
</Macro>
#Use AddFastExt php
#UndefMacro AddFastExt

<Macro AddPhpExt $ext>
  AddType application/x-httpd-php $ext
</Macro>
#Use AddPhpExt php
#UndefMacro AddPhpExt


# Remove extension
<Macro NoExt $ext>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME}.$ext -f
  RewriteRule ^(.+)$ /$1.$ext [L,QSA]
</Macro>

The first one is for FastCGI, and the other one for mod_php, and NoExt is just removing it…

Adding a site

So, to add a site to this… Set up some folders. Virtualhost’s are kept in /srv/www.

Example:

sudo mkdir -p /srv/www/yoursite.dev/{backups,cgi-bin,logs,misc_files,public_html,tmp}
sudo chmod -R $USER:staff /srv/www/yoursite.dev

The files needed are:

  • vhost file: /etc/httpd/conf/sites-available/yoursite.dev.conf (symlinked in to “sites-enabled”)
  • fpm-pool: /etc/php56/fpm/pool.d-available/yoursite.dev.conf (symlinked in to “pool.d”)

The virtualhost…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#===============================================
# yoursite.dev
#===============================================
<VirtualHost *:80>
  Define vhost_srv yoursite.dev
  #Define vhost_adm admin@$vhost_srv

  ServerName ${vhost_srv}
  ServerAlias www.${vhost_srv}
  ServerAdmin webmaster@${vhost_srv}

  DocumentRoot /srv/www/${vhost_srv}/public_html

    ErrorLog /srv/www/${vhost_srv}/logs/error_log
    CustomLog /srv/www/${vhost_srv}/logs/access_log combined

  <IfModule alias_module>
      #Alias /pma /srv/www/_phpMyAdmin/public_html
      ScriptAlias /cgi-bin/ "/srv/www/${vhost_srv}/cgi-bin/"
  </IfModule>

  <Directory "/srv/www/${vhost_srv}/public_html">
      Options -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
      Require host localhost
      Require ip 127
      Require ip ::1
      #Require all granted

      Use NoExt php
  </Directory>

  # Choose PHP Version
  # ==================
  Use FastPHP ${vhost_srv}
  #Use ModPHP
</VirtualHost>

Really easy with just Define vhost_srv yoursite.dev to set.

The pool

Here you can remove anything that is commented or not in use. If no value it will be used from the global file.

Like with the Macros, you can use what you put in the [poolname] as a variable throughout the pool.

Set the pool:

[yoursite.dev]

Set user/group

user = YourName
group = _www

listen.owner = YourName
listen.group = _www
listen.mode = 0660

The sock is set to $pool.sock:

listen = /var/php56/fpm.d/$pool.sock

And your socket name will be yoursite.dev.sock - like it was made in the Vhost/Macro.

yoursite.dev.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ; 
;;;;;;;;;;;;;;;;;;;;
; www.conf :: tlp. ; 
;;;;;;;;;;;;;;;;;;;;

; Multiple pools of child processes may be started with different listening
; ports and different management options.  The name of the pool will be
; used in logs and stats. There is no limitation on the number of pools which
; FPM can handle. Your system will tell you anyway :)

; Start a new pool named 'www'.
; the variable $pool can we used in any directive and will be replaced by the
; pool name ('www' here)
[yoursite.dev]

; Per pool prefix
; It only applies on the following directives:
; - 'slowlog'
; - 'listen' (unixsocket)
; - 'chroot'
; - 'chdir'
; - 'php_values'
; - 'php_admin_values'
; When not set, the global prefix (or /usr/local/php56) applies instead.
; Note: This directive can also be relative to the global prefix.
; Default Value: none
;prefix = /path/to/pools/$pool

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = YourName
group = _www

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses on a
;                            specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
;listen = 127.0.0.1:9000
listen = /var/php56/fpm.d/$pool.sock


; Set listen(2) backlog.
; Default Value: 65535 (-1 on FreeBSD and OpenBSD)
;listen.backlog = 65535

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions. 
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = YourName
listen.group = _www
listen.mode = 0660

; List of ipv4 addresses of FastCGI clients which are allowed to connect.
; Equivalent to the FCGI_WEB_SERVER_ADDRS environment variable in the original
; PHP FCGI (5.2.2+). Makes sense only with a tcp listening socket. Each address
; must be separated by a comma. If this value is left blank, connections will be
; accepted from any ip address.
; Default Value: any
;listen.allowed_clients = 127.0.0.1

; Specify the nice(2) priority to apply to the pool processes (only if set)
; The value can vary from -19 (highest priority) to 20 (lower priority)
; Note: - It will only work if the FPM master process is launched as root
;       - The pool processes will inherit the master process priority
;         unless it specified otherwise
; Default Value: no set
; process.priority = -19

; Choose how the process manager will control the number of child processes.
; Possible Values:
;   static  - a fixed number (pm.max_children) of child processes;
;   dynamic - the number of child processes are set dynamically based on the
;             following directives. With this process management, there will be
;             always at least 1 children.
;             pm.max_children      - the maximum number of children that can
;                                    be alive at the same time.
;             pm.start_servers     - the number of children created on startup.
;             pm.min_spare_servers - the minimum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is less than this
;                                    number then some children will be created.
;             pm.max_spare_servers - the maximum number of children in 'idle'
;                                    state (waiting to process). If the number
;                                    of 'idle' processes is greater than this
;                                    number then some children will be killed.
;  ondemand - no children are created at startup. Children will be forked when
;             new requests will connect. The following parameter are used:
;             pm.max_children           - the maximum number of children that
;                                         can be alive at the same time.
;             pm.process_idle_timeout   - The number of seconds after which
;                                         an idle process will be killed.
; Note: This value is mandatory.
pm = ondemand

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 5

; The number of child processes created on startup.
; Note: Used only when pm is set to 'dynamic'
; Default Value: min_spare_servers + (max_spare_servers - min_spare_servers) / 2
pm.start_servers = 2

; The desired minimum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.min_spare_servers = 1

; The desired maximum number of idle server processes.
; Note: Used only when pm is set to 'dynamic'
; Note: Mandatory when pm is set to 'dynamic'
pm.max_spare_servers = 3

; The number of seconds after which an idle process will be killed.
; Note: Used only when pm is set to 'ondemand'
; Default Value: 10s
;pm.process_idle_timeout = 10s;

; The number of requests each child process should execute before respawning.
; This can be useful to work around memory leaks in 3rd party libraries. For
; endless request processing specify '0'. Equivalent to PHP_FCGI_MAX_REQUESTS.
; Default Value: 0
;pm.max_requests = 500

; The URI to view the FPM status page. If this value is not set, no URI will be
; recognized as a status page. It shows the following informations:
;   pool                 - the name of the pool;
;   process manager      - static, dynamic or ondemand;
;   start time           - the date and time FPM has started;
;   start since          - number of seconds since FPM has started;
;   accepted conn        - the number of request accepted by the pool;
;   listen queue         - the number of request in the queue of pending
;                          connections (see backlog in listen(2));
;   max listen queue     - the maximum number of requests in the queue
;                          of pending connections since FPM has started;
;   listen queue len     - the size of the socket queue of pending connections;
;   idle processes       - the number of idle processes;
;   active processes     - the number of active processes;
;   total processes      - the number of idle + active processes;
;   max active processes - the maximum number of active processes since FPM
;                          has started;
;   max children reached - number of times, the process limit has been reached,
;                          when pm tries to start more children (works only for
;                          pm 'dynamic' and 'ondemand');
; Value are updated in real time.
; Example output:
;   pool:                 www
;   process manager:      static
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          62636
;   accepted conn:        190460
;   listen queue:         0
;   max listen queue:     1
;   listen queue len:     42
;   idle processes:       4
;   active processes:     11
;   total processes:      15
;   max active processes: 12
;   max children reached: 0
;
; By default the status page output is formatted as text/plain. Passing either
; 'html', 'xml' or 'json' in the query string will return the corresponding
; output syntax. Example:
;   http://www.foo.bar/status
;   http://www.foo.bar/status?json
;   http://www.foo.bar/status?html
;   http://www.foo.bar/status?xml
;
; By default the status page only outputs short status. Passing 'full' in the
; query string will also return status for each pool process.
; Example: 
;   http://www.foo.bar/status?full
;   http://www.foo.bar/status?json&full
;   http://www.foo.bar/status?html&full
;   http://www.foo.bar/status?xml&full
; The Full status returns for each process:
;   pid                  - the PID of the process;
;   state                - the state of the process (Idle, Running, ...);
;   start time           - the date and time the process has started;
;   start since          - the number of seconds since the process has started;
;   requests             - the number of requests the process has served;
;   request duration     - the duration in µs of the requests;
;   request method       - the request method (GET, POST, ...);
;   request URI          - the request URI with the query string;
;   content length       - the content length of the request (only with POST);
;   user                 - the user (PHP_AUTH_USER) (or '-' if not set);
;   script               - the main script called (or '-' if not set);
;   last request cpu     - the %cpu the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because CPU calculation is done when the request
;                          processing has terminated;
;   last request memory  - the max amount of memory the last request consumed
;                          it's always 0 if the process is not in Idle state
;                          because memory calculation is done when the request
;                          processing has terminated;
; If the process is in Idle state, then informations are related to the
; last request the process has served. Otherwise informations are related to
; the current request being served.
; Example output:
;   ************************
;   pid:                  31330
;   state:                Running
;   start time:           01/Jul/2011:17:53:49 +0200
;   start since:          63087
;   requests:             12808
;   request duration:     1250261
;   request method:       GET
;   request URI:          /test_mem.php?N=10000
;   content length:       0
;   user:                 -
;   script:               /home/fat/web/docs/php/test_mem.php
;   last request cpu:     0.00
;   last request memory:  0
;
; Note: There is a real-time FPM status monitoring sample web page available
;       It's available in: /usr/share/php56/fpm/status.html
;
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set 
pm.status_path = /p56/status

; The ping URI to call the monitoring page of FPM. If this value is not set, no
; URI will be recognized as a ping page. This could be used to test from outside
; that FPM is alive and responding, or to
; - create a graph of FPM availability (rrd or such);
; - remove a server from a group if it is not responding (load balancing);
; - trigger alerts for the operating team (24/7).
; Note: The value must start with a leading slash (/). The value can be
;       anything, but it may not be a good idea to use the .php extension or it
;       may conflict with a real PHP file.
; Default Value: not set
ping.path = /p56/ping

; This directive may be used to customize the response of a ping request. The
; response is formatted as text/plain with a 200 response code.
; Default Value: pong
ping.response = pong

; The access log file
; Default: not set
;access.log = log/$pool.access.log

; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request
;      it can accept the following format:
;      - %{user}C for user CPU only
;      - %{system}C for system CPU only
;      - %{total}C  for user + system CPU (default)
;  %d: time taken to serve the request
;      it can accept the following format:
;      - %{seconds}d (default)
;      - %{miliseconds}d
;      - %{mili}d
;      - %{microseconds}d
;      - %{micro}d
;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some exemples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
;  %f: script filename
;  %l: content-length of the request (for POST request only)
;  %m: request method
;  %M: peak of memory allocated by PHP
;      it can accept the following format:
;      - %{bytes}M (default)
;      - %{kilobytes}M
;      - %{kilo}M
;      - %{megabytes}M
;      - %{mega}M
;  %n: pool name
;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o
;      - ....
;  %p: PID of the child that serviced the request
;  %P: PID of the parent of the child that serviced the request
;  %q: the query string 
;  %Q: the '?' character if query string exists
;  %r: the request URI (without the query string, see %q and %Q)
;  %R: remote IP address
;  %s: status (response code)
;  %t: server time the request was received
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;  %T: time the log has been written (the request has finished)
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{mili}d %{kilo}M %C%%"

; The log file for slow requests
; Default Value: not set
; Note: slowlog is mandatory if request_slowlog_timeout is set
slowlog = log/$pool.log.slow

; The timeout for serving a single request after which a PHP backtrace will be
; dumped to the 'slowlog' file. A value of '0s' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_slowlog_timeout = 0

; The timeout for serving a single request after which the worker process will
; be killed. This option should be used when the 'max_execution_time' ini option
; does not stop script execution for some reason. A value of '0' means 'off'.
; Available units: s(econds)(default), m(inutes), h(ours), or d(ays)
; Default Value: 0
;request_terminate_timeout = 0

; Set open file descriptor rlimit.
; Default Value: system defined value
;rlimit_files = 1024

; Set max core size rlimit.
; Possible Values: 'unlimited' or an integer greater or equal to 0
; Default Value: system defined value
;rlimit_core = 0

; Chroot to this directory at the start. This value must be defined as an
; absolute path. When this value is not set, chroot is not used.
; Note: you can prefix with '$prefix' to chroot to the pool prefix or one
; of its subdirectories. If the pool prefix is not set, the global prefix
; will be used instead.
; Note: chrooting is a great security feature and should be used whenever 
;       possible. However, all PHP paths will be relative to the chroot
;       (error_log, sessions.save_path, ...).
; Default Value: not set
;chroot = 

; Chdir to this directory at the start.
; Note: relative path can be used.
; Default Value: current directory or / when chroot
;chdir = /var/www

; Redirect worker stdout and stderr into main error log. If not set, stdout and
; stderr will be redirected to /dev/null according to FastCGI specs.
; Note: on highloaded environement, this can cause some delay in the page
; process time (several ms).
; Default Value: no
catch_workers_output = yes

; Clear environment in FPM workers
; Prevents arbitrary environment variables from reaching FPM worker processes
; by clearing the environment in workers before env vars specified in this
; pool configuration are added.
; Setting to "no" will make all environment variables available to PHP code
; via getenv(), $_ENV and $_SERVER.
; Default Value: yes
;clear_env = no

; Limits the extensions of the main script FPM will allow to parse. This can
; prevent configuration mistakes on the web server side. You should only limit
; FPM to .php extensions to prevent malicious users to use other extensions to
; exectute php code.
; Note: set an empty value to allow all extensions.
; Default Value: .php
;security.limit_extensions = .php .php3 .php4 .php5
security.limit_extensions = .php

; Pass environment variables like LD_LIBRARY_PATH. All $VARIABLEs are taken from
; the current environment.
; Default Value: clean env
;env[HOSTNAME] = $HOSTNAME
;env[PATH] = /usr/local/bin:/usr/bin:/bin
;env[TMP] = /tmp
;env[TMPDIR] = /tmp
;env[TEMP] = /tmp

; Additional php.ini defines, specific to this pool of workers. These settings
; overwrite the values previously defined in the php.ini. The directives are the
; same as the PHP SAPI:
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'. 
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'
; For php_*flag, valid values are on, off, 1, 0, true, false, yes or no.

; Defining 'extension' will load the corresponding shared extension from
; extension_dir. Defining 'disable_functions' or 'disable_classes' will not
; overwrite previously defined php.ini values, but will append the new value
; instead.

; Note: path INI options can be relative and will be expanded with the prefix
; (pool, global or /usr/local/php56)

; Default Value: nothing is defined by default except the values in php.ini and
; specified at startup with the -d argument

;;; Mail
;php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i
php_admin_value[mail.log] = /srv/www/$pool/logs/$pool-php_mail_log

;;; Errors
php_flag[display_errors] = on
php_admin_value[error_log] = /srv/www/$pool/logs/$pool-php_errors_log
php_admin_flag[log_errors] = on

;;; Mem
;php_admin_value[memory_limit] = 128M
php_admin_value[memory_limit] = 32M

;; Session
php_admin_value[session.gc_maxlifetime] = 3600
;php_admin_value[session.save_path] = /srv/www/$pool/tmp
;php_admin_value[session.save_path] = /var/php56/var/session

;;; Dirs
;php_admin_value[open_basedir] = /srv/www/$pool/public_html
;php_admin_value[upload_tmp_dir] = /srv/www/$pool/tmp

In the end of the pool, you can play around with memory values etc… You might want to bumb it up a bit.

The setting:

security.limit_extensions = .php

In the example you can’t use anything else than .php. To add more, just add the in the end with a space between.

security.limit_extensions = .php .srv .foo .bar

Comment out the line to remove the restriction.

You can also look in part 2 at the httpd-info.conf. There are the settings for the FPM status pages.

  • yoursite.dev/p56 (status.html)
  • yoursite.dev/p56/status
  • yoursite.dev/p56/ping (pong)

There are also more/full examples of the files (Macros etc) in part 2.

Restarting FPM

When you make changes to the server you need to restart it with apachectl, but also the FPM. I made a script out of apachectl -> fpmctl. I wrote about it here: Custom Script to Start/stop PHP-FPM.

It restarts the LaunchDaemon that makes PHP-FPM start on boot.

net.php.php-fpm.plist
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<plist version="1.0">
<dict>
  <key>KeepAlive</key>
  <false/>
  <key>Label</key>
  <string>net.php.php-fpm</string>
  <key>LaunchOnlyOnce</key>
  <true/>
  <key>ProgramArguments</key>
  <array>
      <string>/usr/local/php56/sbin/php-fpm</string>
      <string>--fpm-config</string>
      <string>/etc/php56/php-fpm.conf</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>Debug</key>
  <false/>
  <key>ServiceDescription</key>
  <string>PHP 5.6 :: FPM/FastCGI</string>
  <key>StandardErrorPath</key>
  <string>/var/php56/log/php-fpm.log</string>
</dict>
</plist>

To unload/load it…

sudo launchctl unload -w /System/Library/LaunchDaemons/net.php.php-fpm.plist
sudo launchctl load -w /System/Library/LaunchDaemons/net.php.php-fpm.plist

Note: With El Capitan you have the new SIP protection, so you might want to use /Library or ~/Library instead, since the system area is protected. Another solution is of course to disable SIP.

Also… Read the FPM manual at php.net.

Sumup

There are many ways to setup FPM/FastCGI. Using proxy or not… Using “Suexec” or not… This is the way I did it. I think it gives me the most options, and the easiest way to be able to use it the way I want. It also reminds most of the old traditional way.

With the use of the Macro functions in Apache 2.4 it’s really easy to template the settings so each virtualhost/pool doesn’t need that much of editing or content. The xtra pools you can really trim down - I pasted the full file just so you can see what it’s all about.

Make sure you have good settings and permissions on the folders and files and “make a plan”. Don’t think you will install this in a day or week. It’s most likely you’ll end up doing something else instead. But a good plan, and a ton of patience… it’s well worth it. :)

That feeling you get when it’s done is “priceless”. All done by your self - exactly the way you wanted.


If you scan the blog you’ll find a few post with scripts and helpers. Updating the GeoIP database etc.

Like I said in the first post… This is more an overview of my setup. I have tried to include a lot, but some parts may be missing. I’ve had this setup now for a while, just updating it to new versions as they come. It’s been quite easy and not too much effort doing it. Of course, to manually compile a PHP version takes a half an hour or so, and same thing with Apache. Then adding the extensions (not always needed), and the modules when you update Apache. Doing all 3 + all xtras will take a couple of three hours. Sometimes faster and sometimes even longer.

You might want to go back to part 2 and look att the httpd.conf and som other settings there. There are some tweaks for FPM etc.


Memory

Using mod_php with “Prefork” in Apache can beef up the memory quite a bit. I don’t remember exactly, but it was over 80MB something. Now, with Apache using the MPM “Event”, the memory footprint is down to 20MB (with my settings, your may be different). The php-fpm is about 14MB - which is ok.

Note: These number are from a booted server which been up a few hours with merely no traffic/load. More or less the previews when writing this post.

MySQL

To round off things here… I won’t cover any “phpMyAdmin” or “Adminer” setup. I have mention Adminer a bit in part 2, but both are actually not a part of the server - they’re just web interfaces - GUI’s.

To install MySQL &/or MariaDB, Postgresql (included in OS X). MySQL comes with an installer. Use that one and st up a few aliases to start stop. I think I have mentioned the LaunchDaemon to make it start on boot, or I’ll write a post on that later.

If you go with Adminer… It’s really easy to set up. Read the installation on their page.

For both PMA and Adminer, you can set them up as individual virtualhosts, or you can put them in /usr/share/webapps/{adminer,phpmyadmin} and the use en alias in Apache or per virtualhost. There’s no best way - just what you prefer.

If you look in part 2 there’s an Adminer example with its own conf file. That’s the way I use it now.


Now, this is all on OS X - the way I set it up in my version. I guess most of the info and settings can be used in Linux/*BSD as well - as a concept/overview, picka bits and part from. It’s just about to keep track of the file/folder paths.

When I move to Linux (soon), I’ll probably make a couple of other posts how I set it up there.


Happy hacking…

/Eric

Comments