forked from ryannix123/openemr-on-openshift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainerfile
More file actions
841 lines (724 loc) · 29 KB
/
Copy pathContainerfile
File metadata and controls
841 lines (724 loc) · 29 KB
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# OpenEMR Container - CentOS 10 Stream with Remi PHP 8.5
# Multi-stage build for optimized final image
# Runs nginx + PHP-FPM in single container with supervisord
# ============================================================================
# Stage 1: Builder - Download and prepare OpenEMR
# ============================================================================
FROM quay.io/centos/centos:stream10 AS builder
# OpenEMR version
ARG OPENEMR_VERSION=8.0.0
# Enable EPEL and CRB repositories for additional packages
# Note: CentOS Stream 10 has GPG key crypto-policy issues, using --nogpgcheck for epel-release
RUN dnf install -y --nogpgcheck epel-release \
&& dnf install -y dnf-plugins-core \
&& dnf config-manager --set-enabled crb \
&& dnf clean all
# Install Remi's repository for PHP 8.5
# Note: Using --nogpgcheck due to CentOS Stream 10 crypto-policy compatibility
RUN dnf install -y --nogpgcheck \
https://rpms.remirepo.net/enterprise/remi-release-10.rpm \
&& dnf clean all
# Enable Remi's PHP 8.5 repository
RUN dnf module reset php -y \
&& dnf module enable php:remi-8.5 -y
# Install build dependencies and tools
RUN dnf install -y \
git \
unzip \
php-cli \
php-json \
php-mbstring \
php-xml \
php-zip \
&& dnf clean all
# Install Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Clone OpenEMR from GitHub (shallow clone of specific tag)
WORKDIR /tmp
RUN git clone https://github.com/openemr/openemr.git --branch v8_0_0 --depth 1
# Install PHP dependencies with Composer
WORKDIR /tmp/openemr
RUN composer install --no-dev --no-interaction --optimize-autoloader
# Remove unnecessary files to reduce image size
RUN cd /tmp/openemr && \
rm -rf .git .github .travis* tests docker contrib/util/docker \
&& find . -type f -name "*.md" -delete \
&& find . -type f -name "*.jar" -delete \
&& find . -type f -name "*.war" -delete
# Verify InstallerAuto.php exists before proceeding
RUN test -f /tmp/openemr/contrib/util/installScripts/InstallerAuto.php \
&& echo "✓ InstallerAuto.php found" \
|| (echo "ERROR: InstallerAuto.php not found!" && exit 1)
# ============================================================================
# Stage 2: Runtime - Build final container
# ============================================================================
FROM quay.io/centos/centos:stream10
LABEL maintainer="Ryan Nix <ryan_nix>" \
description="OpenEMR on CentOS 10 Stream - OpenShift Ready" \
version="8.0.0" \
io.k8s.description="OpenEMR Electronic Medical Records System" \
io.openshift.tags="openemr,healthcare,php,medical" \
io.openshift.expose-services="8080:http" \
app.openshift.io/runtime=php
# Environment variables
ENV OPENEMR_VERSION=8.0.0 \
OPENEMR_WEB_ROOT=/var/www/html/openemr \
PHP_FPM_PORT=9000 \
NGINX_PORT=8080 \
PHP_VERSION=8.5
# Enable EPEL and CRB repositories
# Note: CentOS Stream 10 has GPG key crypto-policy issues, using --nogpgcheck for epel-release
RUN dnf install -y --nogpgcheck epel-release \
&& dnf install -y dnf-plugins-core \
&& dnf config-manager --set-enabled crb \
&& dnf clean all
# Update all packages to get security patches
RUN dnf upgrade -y && dnf clean all
# Install Remi's repository for PHP 8.5
# Note: Using --nogpgcheck due to CentOS Stream 10 crypto-policy compatibility
RUN dnf install -y --nogpgcheck \
https://rpms.remirepo.net/enterprise/remi-release-10.rpm \
&& dnf clean all
# Enable Remi's PHP 8.5 repository and reset PHP module
RUN dnf module reset php -y \
&& dnf module enable php:remi-8.5 -y
# Install nginx
RUN dnf install -y nginx && dnf clean all
# Install PHP 8.5 and all required modules for OpenEMR from Remi's repo
RUN dnf install -y \
# PHP Core
php \
php-fpm \
php-cli \
php-common \
# Database
php-mysqlnd \
php-pdo \
# OpenEMR Required Extensions
php-gd \
php-xml \
php-mbstring \
php-json \
php-zip \
php-curl \
php-opcache \
php-ldap \
php-soap \
php-bcmath \
php-intl \
# OpenEMR Recommended Extensions
php-imap \
php-tidy \
php-xmlrpc \
php-sodium \
# Session handling
php-pecl-redis5 \
# Process management
supervisor \
# Utilities
unzip \
wget \
which \
&& dnf clean all \
&& rm -rf /var/cache/dnf
# Install Node.js 22 (required for OpenEMR frontend build)
# Note: CentOS Stream 10 uses direct package installation, not module streams
RUN dnf install -y nodejs22 npm \
&& dnf clean all \
&& node --version && npm --version
# Copy OpenEMR from builder stage
COPY --from=builder /tmp/openemr ${OPENEMR_WEB_ROOT}
# Verify InstallerAuto.php was copied
RUN test -f ${OPENEMR_WEB_ROOT}/contrib/util/installScripts/InstallerAuto.php \
&& echo "✓ InstallerAuto.php present in final image"
# Build OpenEMR frontend assets
WORKDIR ${OPENEMR_WEB_ROOT}
RUN npm install --legacy-peer-deps \
&& npm run build \
&& rm -rf node_modules \
&& echo "✓ Frontend assets built successfully"
# Install CCDA/CQM service dependencies (Node.js microservices for
# C-CDA document exchange and Clinical Quality Measures reporting)
# These run as a supervised process alongside nginx and PHP-FPM
RUN cd ${OPENEMR_WEB_ROOT}/ccdaservice \
&& npm install --legacy-peer-deps \
&& echo "✓ CCDA/CQM service dependencies installed"
# Fix relative path resolution for nginx + PHP-FPM
# Apache mod_php auto-sets CWD to the script's directory on each request;
# PHP-FPM does not, which breaks OpenEMR's relative require paths (e.g., ../globals.php).
# This prepend script restores that behavior.
RUN cat > ${OPENEMR_WEB_ROOT}/auto_prepend.php <<'EOF'
<?php
chdir(dirname($_SERVER['SCRIPT_FILENAME']));
EOF
# ============================================================================
# PHP Configuration
# ============================================================================
# Create custom PHP configuration for OpenEMR
RUN cat > /etc/php.d/99-openemr.ini <<'EOF'
; OpenEMR PHP Configuration
; File Upload Settings (for medical documents, images, lab results)
upload_max_filesize = 128M
post_max_size = 128M
max_input_vars = 3000
; Memory and Execution
memory_limit = 512M
max_execution_time = 300
max_input_time = 300
; Session Configuration (Redis-backed for multi-pod deployments)
session.save_handler = redis
session.save_path = "tcp://redis:6379"
session.gc_maxlifetime = 7200
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1
; Error Handling (Production)
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
log_errors = On
error_log = /dev/stderr
; Security
expose_php = Off
allow_url_fopen = On
allow_url_include = Off
; Date/Time
date.timezone = UTC
; Working directory fix for nginx + PHP-FPM
; OpenEMR uses relative paths (e.g., ../globals.php) that require
; the CWD to match the script's directory, as Apache mod_php does
auto_prepend_file = /var/www/html/openemr/auto_prepend.php
; OPcache (Performance)
opcache.enable = 1
opcache.memory_consumption = 256
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 10000
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.save_comments = 1
opcache.fast_shutdown = 1
EOF
# ============================================================================
# PHP-FPM Configuration
# ============================================================================
RUN cat > /etc/php-fpm.d/www.conf <<'EOF'
[www]
; Unix socket or TCP (we use TCP for easier container networking)
listen = 127.0.0.1:9000
; Process ownership (OpenShift uses arbitrary UIDs, group 0)
listen.owner = nginx
listen.group = root
listen.mode = 0660
; Process manager configuration
user = nginx
group = root
; Dynamic process management
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.process_idle_timeout = 10s
pm.max_requests = 500
; Logging
access.log = /dev/stdout
catch_workers_output = yes
decorate_workers_output = no
; Health check endpoint
pm.status_path = /fpm-status
ping.path = /fpm-ping
ping.response = pong
; Session configuration (Redis)
php_value[session.save_handler] = redis
php_value[session.save_path] = "tcp://redis:6379"
php_value[session.gc_maxlifetime] = 7200
; Security
php_admin_flag[log_errors] = on
php_admin_value[error_log] = /dev/stderr
EOF
# ============================================================================
# nginx Configuration
# ============================================================================
RUN cat > /etc/nginx/nginx.conf <<'EOF'
# nginx configuration for OpenEMR
user nginx;
worker_processes auto;
error_log /dev/stderr warn;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /dev/stdout main;
# Performance
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip Compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml application/json application/javascript
application/xml application/xml+rss text/javascript application/x-font-ttf
font/opentype image/svg+xml;
server {
listen 8080 default_server;
listen [::]:8080 default_server;
server_name _;
root /var/www/html/openemr;
index index.php index.html;
# Health check endpoints
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
location /fpm-status {
access_log off;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# OpenEMR Zend Module routes (Manage Modules, Carecoordination, etc.)
location /interface/modules/zend_modules {
try_files $uri $uri/ /interface/modules/zend_modules/public/index.php?$query_string;
}
# OpenEMR main application
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP processing
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# Increased timeouts for long-running reports
fastcgi_read_timeout 300;
fastcgi_send_timeout 300;
}
# Deny access to sensitive files
location ~ /\.ht {
deny all;
}
location ~ /\.git {
deny all;
}
# OpenEMR specific denies
location ~ ^/sites/.*/documents {
deny all;
}
location ~ ^/sites/default/sqlconf.php {
deny all;
}
# Allow larger uploads for medical documents
client_max_body_size 128M;
client_body_buffer_size 128k;
}
}
EOF
# ============================================================================
# Supervisor Configuration (manages nginx + PHP-FPM + CCDA/CQM service)
# ============================================================================
RUN mkdir -p /var/log/supervisor
RUN cat > /etc/supervisord.conf <<'EOF'
[supervisord]
nodaemon=true
logfile=/dev/stdout
logfile_maxbytes=0
loglevel=info
pidfile=/run/supervisord.pid
[program:php-fpm]
command=/usr/sbin/php-fpm --nodaemonize --fpm-config /etc/php-fpm.conf
autostart=true
autorestart=true
priority=5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
stdout_events_enabled=true
stderr_events_enabled=true
[program:nginx]
command=/usr/sbin/nginx -g 'daemon off;'
autostart=true
autorestart=true
priority=10
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
stdout_events_enabled=true
stderr_events_enabled=true
[program:ccda-service]
command=node /var/www/html/openemr/ccdaservice/serveccda.js
directory=/var/www/html/openemr/ccdaservice
autostart=true
autorestart=true
priority=15
startsecs=5
startretries=3
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
stdout_events_enabled=true
stderr_events_enabled=true
[program:cqm-service]
command=node /var/www/html/openemr/ccdaservice/node_modules/oe-cqm-service/server.js
directory=/var/www/html/openemr/ccdaservice/node_modules/oe-cqm-service
autostart=true
autorestart=true
priority=15
startsecs=5
startretries=3
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
stdout_events_enabled=true
stderr_events_enabled=true
EOF
# ============================================================================
# OpenShift Permissions and Security
# ============================================================================
# Create necessary directories with proper permissions
RUN mkdir -p \
/var/log/php-fpm \
/var/log/nginx \
/var/lib/nginx \
/var/lib/php/session \
/run/php-fpm \
/tmp/sessions \
${OPENEMR_WEB_ROOT}/sites/default/documents \
&& chmod -R 775 /tmp/sessions
# OpenShift runs containers with arbitrary UIDs but always group 0 (root)
# Need to give group 0 same permissions as owner
RUN chgrp -R 0 \
${OPENEMR_WEB_ROOT} \
/var/log/nginx \
/var/log/php-fpm \
/var/lib/nginx \
/var/lib/php \
/run \
/tmp/sessions \
/etc/nginx \
/etc/php-fpm.d \
&& chmod -R g=u \
${OPENEMR_WEB_ROOT} \
/var/log/nginx \
/var/log/php-fpm \
/var/lib/nginx \
/var/lib/php \
/run \
/tmp/sessions \
/etc/nginx \
/etc/php-fpm.d
# Make specific OpenEMR directories writable
RUN chmod -R 770 ${OPENEMR_WEB_ROOT}/sites/default/documents \
&& chmod -R 770 ${OPENEMR_WEB_ROOT}/sites \
&& chmod -R 770 ${OPENEMR_WEB_ROOT}/interface/modules/zend_modules/config \
&& mkdir -p ${OPENEMR_WEB_ROOT}/sites/default/documents/logs_and_misc/methods \
&& chmod -R 770 ${OPENEMR_WEB_ROOT}/sites/default/documents/logs_and_misc
# Backup sites/default for PVC initialization
# When a PVC is mounted at sites/default, it will be empty on first run
# The entrypoint will restore these files to initialize the PVC
RUN cp -a ${OPENEMR_WEB_ROOT}/sites/default /opt/openemr-sites-default-backup \
&& chgrp -R 0 /opt/openemr-sites-default-backup \
&& chmod -R g=u /opt/openemr-sites-default-backup
# Create entrypoint script
RUN cat > /entrypoint.sh <<'ENTRYPOINT'
#!/bin/bash
set -e
echo "=========================================="
echo "Starting OpenEMR Container"
echo "=========================================="
echo "OpenEMR Version: ${OPENEMR_VERSION}"
echo "PHP Version: $(php -v | head -n 1)"
echo "Web Root: ${OPENEMR_WEB_ROOT}"
echo ""
echo "Configuration:"
echo " - PHP-FPM: 127.0.0.1:${PHP_FPM_PORT}"
echo " - nginx: 0.0.0.0:${NGINX_PORT}"
echo " - UID: $(id -u), GID: $(id -g)"
echo "=========================================="
# Initialize PVC if empty (first run with freshly mounted PVC)
# Check if config.php exists - if not, PVC is empty and needs initialization
# We check config.php (not sqlconf.php) because config.php is static and only exists after restore
echo "Checking if site files need to be restored..."
if [ ! -f "${OPENEMR_WEB_ROOT}/sites/default/config.php" ]; then
echo "Site files missing - initializing from backup..."
if [ -d "/opt/openemr-sites-default-backup" ]; then
cp -a /opt/openemr-sites-default-backup/* ${OPENEMR_WEB_ROOT}/sites/default/
echo "✓ Site files restored from backup"
else
echo "⚠ No backup found at /opt/openemr-sites-default-backup"
fi
else
echo "✓ Site files already present"
fi
# Ensure permissions are correct (OpenShift may assign random UID)
echo "Setting permissions for UID $(id -u)..."
chmod -R g=u ${OPENEMR_WEB_ROOT}/sites 2>/dev/null || true
chmod -R g=u /tmp/sessions 2>/dev/null || true
chmod -R g=u /var/lib/php/session 2>/dev/null || true
# Create crypto keys directory (may be on mounted PVC, so create at runtime)
mkdir -p ${OPENEMR_WEB_ROOT}/sites/default/documents/logs_and_misc/methods 2>/dev/null || true
chmod -R 770 ${OPENEMR_WEB_ROOT}/sites/default/documents/logs_and_misc 2>/dev/null || true
# Test Redis connectivity and fall back to file sessions if needed
echo "Testing session storage..."
if php -r "try { \$r = new Redis(); \$r->connect('redis', 6379, 2); echo 'OK'; } catch (Exception \$e) { echo 'FAIL'; exit(1); }" 2>/dev/null; then
echo "✓ Redis session storage available"
else
echo "⚠ Redis unavailable, falling back to file-based sessions"
# Update PHP-FPM to use file sessions
sed -i 's|php_value\[session.save_handler\] = redis|php_value\[session.save_handler\] = files|' /etc/php-fpm.d/www.conf
sed -i 's|php_value\[session.save_path\].*|php_value\[session.save_path\] = "/var/lib/php/session"|' /etc/php-fpm.d/www.conf
fi
# Check if OpenEMR is already configured (look for $config = 1 in sqlconf.php)
SQLCONF="${OPENEMR_WEB_ROOT}/sites/default/sqlconf.php"
INSTALLER="${OPENEMR_WEB_ROOT}/contrib/util/installScripts/InstallerAuto.php"
# Debug: Show what files exist
echo "Checking configuration status..."
echo " - sqlconf.php exists: $(test -f "$SQLCONF" && echo 'yes' || echo 'no')"
echo " - InstallerAuto.php exists: $(test -f "$INSTALLER" && echo 'yes' || echo 'no')"
# Set database credentials from environment (with defaults)
export MYSQL_HOST=${MYSQL_HOST:-mariadb}
export MYSQL_PORT=${MYSQL_PORT:-3306}
export MYSQL_DATABASE=${MYSQL_DATABASE:-openemr}
export MYSQL_USER=${MYSQL_USER:-openemr}
export MYSQL_PASS=${MYSQL_PASS:-openemr}
export OE_USER=${OE_USER:-admin}
export OE_PASS=${OE_PASS:-pass}
# ─── Helper: Write real credentials into sqlconf.php ───
# This ensures sqlconf.php always has the correct credentials from the
# environment, regardless of whether InstallerAuto.php succeeds or fails.
update_sqlconf_credentials() {
if [ -f "$SQLCONF" ]; then
echo "Syncing sqlconf.php with environment credentials..."
sed -i "s|\\\$host[[:space:]]*=.*|\\\$host = '${MYSQL_HOST}';|" "$SQLCONF"
sed -i "s|\\\$port[[:space:]]*=.*|\\\$port = '${MYSQL_PORT}';|" "$SQLCONF"
sed -i "s|\\\$login[[:space:]]*=.*|\\\$login = '${MYSQL_USER}';|" "$SQLCONF"
sed -i "s|\\\$pass[[:space:]]*=.*|\\\$pass = '${MYSQL_PASS}';|" "$SQLCONF"
sed -i "s|\\\$dbase[[:space:]]*=.*|\\\$dbase = '${MYSQL_DATABASE}';|" "$SQLCONF"
echo "✓ sqlconf.php credentials updated"
fi
}
# ─── Helper: Check if database has OpenEMR tables ───
db_has_tables() {
php -r "
\$c = @mysqli_connect('${MYSQL_HOST}', '${MYSQL_USER}', '${MYSQL_PASS}', '${MYSQL_DATABASE}', (int)'${MYSQL_PORT}');
if (!\$c) exit(1);
\$r = mysqli_query(\$c, \"SELECT COUNT(*) as cnt FROM information_schema.tables WHERE table_schema='${MYSQL_DATABASE}'\");
\$row = mysqli_fetch_assoc(\$r);
exit(\$row['cnt'] > 10 ? 0 : 1);
" 2>/dev/null
}
# ─── Helper: Check if install is COMPLETE (not just tables created) ───
# The installer creates tables first, then seeds globals/data. If the pod
# restarts mid-install, tables exist but globals is empty = broken state.
db_install_complete() {
php -r "
\$c = @mysqli_connect('${MYSQL_HOST}', '${MYSQL_USER}', '${MYSQL_PASS}', '${MYSQL_DATABASE}', (int)'${MYSQL_PORT}');
if (!\$c) exit(1);
\$r = mysqli_query(\$c, \"SELECT COUNT(*) as cnt FROM globals\");
if (!\$r) exit(1);
\$row = mysqli_fetch_assoc(\$r);
// A complete install has 300+ globals rows; partial has 0-5
exit(\$row['cnt'] > 100 ? 0 : 1);
" 2>/dev/null
}
# ─── Helper: Drop all tables for clean re-install ───
# Used when a partial install left tables but no seed data
db_drop_all_tables() {
echo "Dropping all tables from incomplete install..."
php -r "
\$c = @mysqli_connect('${MYSQL_HOST}', '${MYSQL_USER}', '${MYSQL_PASS}', '${MYSQL_DATABASE}', (int)'${MYSQL_PORT}');
if (!\$c) { echo 'Could not connect to drop tables' . PHP_EOL; exit(1); }
mysqli_query(\$c, 'SET FOREIGN_KEY_CHECKS = 0');
\$r = mysqli_query(\$c, \"SELECT table_name FROM information_schema.tables WHERE table_schema='${MYSQL_DATABASE}'\");
\$count = 0;
while (\$row = mysqli_fetch_assoc(\$r)) {
mysqli_query(\$c, 'DROP TABLE IF EXISTS \`' . \$row['table_name'] . '\`');
\$count++;
}
mysqli_query(\$c, 'SET FOREIGN_KEY_CHECKS = 1');
echo \"Dropped \$count tables\" . PHP_EOL;
" 2>/dev/null
}
# ─── Helper: Enable C-CDA/CQM connector ───
enable_ccda_connector() {
echo "Enabling C-CDA service connector..."
php -r "
require '${OPENEMR_WEB_ROOT}/sites/default/sqlconf.php';
\$conn = mysqli_connect(\$host, \$login, \$pass, \$dbase, (int)\$port);
if (\$conn) {
mysqli_query(\$conn, \"INSERT INTO globals (gl_name, gl_index, gl_value) VALUES ('ccda_alt_service_enable', 0, '3') ON DUPLICATE KEY UPDATE gl_value='3'\");
echo '✓ C-CDA service connector enabled' . PHP_EOL;
mysqli_close(\$conn);
} else {
echo '⚠ Could not enable C-CDA connector: ' . mysqli_connect_error() . PHP_EOL;
}
" 2>&1 || echo "⚠ C-CDA connector setup had issues"
}
# Check if already configured ($config = 1 means configured)
ALREADY_CONFIGURED=false
if [ -f "$SQLCONF" ] && grep -q '\$config = 1' "$SQLCONF" 2>/dev/null; then
ALREADY_CONFIGURED=true
echo " - Configuration status: CONFIGURED"
else
echo " - Configuration status: NOT CONFIGURED"
fi
# ─── Case 1: Already configured — sync credentials if needed ───
if [ "$ALREADY_CONFIGURED" = true ]; then
echo "✓ OpenEMR already configured"
# Sync credentials in case PVC outlived the secret (redeployment with new password)
update_sqlconf_credentials
# Verify we can actually connect with these credentials
if php -r "mysqli_connect('${MYSQL_HOST}', '${MYSQL_USER}', '${MYSQL_PASS}', '${MYSQL_DATABASE}', (int)'${MYSQL_PORT}') or exit(1);" 2>/dev/null; then
echo "✓ Database connection verified"
else
echo "⚠ Database connection failed — MariaDB may still be starting"
fi
# ─── Case 2: Not configured, installer available — run auto-config ───
elif [ -f "$INSTALLER" ]; then
echo "=========================================="
echo "Running OpenEMR Auto-Configuration"
echo "=========================================="
echo "Database connection settings:"
echo " - Host: ${MYSQL_HOST}"
echo " - Port: ${MYSQL_PORT}"
echo " - Database: ${MYSQL_DATABASE}"
echo " - User: ${MYSQL_USER}"
echo " - Admin User: ${OE_USER}"
# Write real credentials into sqlconf.php BEFORE running installer
# This ensures the app can connect even if the installer fails partway through
update_sqlconf_credentials
# Wait for database to be ready
echo "Waiting for database at ${MYSQL_HOST}..."
counter=0
while ! php -r "mysqli_connect('${MYSQL_HOST}', '${MYSQL_USER}', '${MYSQL_PASS}', '${MYSQL_DATABASE}') or exit(1);" 2>/dev/null; do
sleep 2
counter=$((counter+1))
echo " Attempt $counter: waiting for database..."
if [ $counter -gt 30 ]; then
echo "ERROR: Database not ready after 60 seconds"
echo "Check that MariaDB pod is running and credentials are correct"
echo "Falling back to manual setup..."
break
fi
done
if [ $counter -le 30 ]; then
echo "✓ Database connection successful"
# Check if this is a retry (tables already exist from a previous partial install)
if db_has_tables; then
if db_install_complete; then
echo "Database has complete OpenEMR install (previous run succeeded)"
echo "Skipping InstallerAuto.php — fixing configuration only..."
sed -i "s|\\\$config = 0.*|\\\$config = 1; ////////////|" "$SQLCONF"
echo "✓ Configuration status set to CONFIGURED"
enable_ccda_connector
else
echo "⚠ Incomplete install detected (tables exist but globals not seeded)"
echo " Cleaning up and re-running installer..."
db_drop_all_tables
# Reset sqlconf.php to unconfigured state for clean install
sed -i "s|\\\$config = 1.*|\\\$config = 0; ////////////|" "$SQLCONF"
echo "Running InstallerAuto.php (no_root_db_access mode)..."
cd ${OPENEMR_WEB_ROOT}
export OPENEMR_ENABLE_INSTALLER_AUTO=1
php -f contrib/util/installScripts/InstallerAuto.php \
no_root_db_access=1 \
server="${MYSQL_HOST}" \
port="${MYSQL_PORT}" \
login="${MYSQL_USER}" \
pass="${MYSQL_PASS}" \
dbname="${MYSQL_DATABASE}" \
iuser="${OE_USER}" \
iuserpass="${OE_PASS}" \
iuname="Administrator" \
2>&1 \
&& echo "✓ Auto-configuration completed successfully!" \
|| echo "⚠ Auto-configuration had issues, check logs above"
# Ensure credentials are correct after installer
update_sqlconf_credentials
if grep -q '\$config = 1' "$SQLCONF" 2>/dev/null; then
echo "✓ OpenEMR configured and ready!"
enable_ccda_connector
else
echo "⚠ Configuration may not be complete - manual setup may be required"
fi
fi
else
# Fresh install — run InstallerAuto.php
echo "Running InstallerAuto.php (no_root_db_access mode)..."
cd ${OPENEMR_WEB_ROOT}
export OPENEMR_ENABLE_INSTALLER_AUTO=1
php -f contrib/util/installScripts/InstallerAuto.php \
no_root_db_access=1 \
server="${MYSQL_HOST}" \
port="${MYSQL_PORT}" \
login="${MYSQL_USER}" \
pass="${MYSQL_PASS}" \
dbname="${MYSQL_DATABASE}" \
iuser="${OE_USER}" \
iuserpass="${OE_PASS}" \
iuname="Administrator" \
2>&1 \
&& echo "✓ Auto-configuration completed successfully!" \
|| echo "⚠ Auto-configuration had issues, check logs above"
# Verify and recover
if grep -q '\$config = 1' "$SQLCONF" 2>/dev/null; then
echo "✓ OpenEMR configured and ready!"
enable_ccda_connector
elif db_has_tables && db_install_complete; then
# Installer created tables and seeded data but didn't update sqlconf.php
echo "⚠ Installer didn't update sqlconf.php — recovering..."
update_sqlconf_credentials
sed -i "s|\\\$config = 0.*|\\\$config = 1; ////////////|" "$SQLCONF"
echo "✓ Configuration recovered"
enable_ccda_connector
else
echo "⚠ Configuration may not be complete - manual setup may be required"
echo " Visit the web interface to complete setup"
fi
fi
echo "=========================================="
fi
# ─── Case 3: No installer available ───
else
echo "⚠ InstallerAuto.php not found - manual setup required"
echo " Visit the web interface to complete setup"
fi
# Start supervisor (manages nginx + PHP-FPM + CCDA/CQM service)
echo "Starting services via supervisord..."
exec /usr/bin/supervisord -c /etc/supervisord.conf
ENTRYPOINT
RUN chmod +x /entrypoint.sh && chgrp 0 /entrypoint.sh && chmod g=u /entrypoint.sh
# ============================================================================
# Health Checks and Metadata
# ============================================================================
# Expose nginx port (8080 for non-root)
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=300s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# Switch to non-root user (OpenShift will override with arbitrary UID)
USER 1001
# Working directory
WORKDIR ${OPENEMR_WEB_ROOT}
# Start supervisor via entrypoint
ENTRYPOINT ["/entrypoint.sh"]