apache + perl + cgi + mysql (DBD::mysql, DBI) on MacBook M1 using Docker

[Japanese(日本語)]

This article shows how to create apache,PerlCgi and mysql(DBD::mysql, DBI) on MacBook M1 using Docker as follows.

 

■1. Create a Docker container.

(1.1)Get Docker image.

docker image pull amd64/ubuntu:focal

(1.2)Create a Docker container.

docker run -p 8080:80 -p 3307:3306 -it -d --name ubuntu amd64/ubuntu:focal

 

■2. Create Docker environment.

(2.1)Login the Docker container.

docker exec -it ubuntu /bin/bash

(2.2)Install needed applications as follows.

apt update
apt install -y apache2
    You may be asked timezone, so answer properly.
apt install -y wget
apt install -y gcc
apt install -y make
apt install -y mysql-server
apt install -y libmysqlclient-dev
apt install libssl-dev
wget https://www.cpan.org/modules/by-module/DBI/DBI-1.643.tar.gz
tar xvzf DBI-1.643.tar.gz
cd DBI-1.643
perl Makefile.PL
make
make install
cpan update
cpan install DBD::mysql
a2enmod cgid

 

Add 2023/4/25

you might also be able to install DBI as follows.

cpan install DBI

instead of following steps.

wget https://www.cpan.org/modules/by-module/DBI/DBI-1.643.tar.gz
tar xvzf DBI-1.643.tar.gz
cd DBI-1.643
perl Makefile.PL
make
make install

 

■3. Create MySQL Database and input sample data.

(3.1)Create Database and user.

mysqld_safe --user=mysql &
mysql -u root
mysql>create database mydb;
mysql>create user 'test'@localhost identified by 'test';
mysql>grant all privileges on mydb.* to 'test'@localhost;
mysql>alter user 'test'@localhost IDENTIFIED WITH mysql_native_password by 'test';
mysql>quit

(3.2)Insert sample data.

mysql -u test -p
mysql>test
mysql>use mydb;
mysql>create table m_id(id varchar(30), name varchar(30));
mysql>insert into m_id values('001','admin'); 
mysql>insert into m_id values('002','Smith'); 
mysql>insert into m_id values('003','Johnson'); 
mysql>insert into m_id values('004','Williams'); 
mysql>commit;
mysql>quit

 

 

■4. Create sample perl CGI.

(4.1)Set perl CGI file as follows.

Path:/usr/lib/cgi-bin/test.cgi
Source:

#!/usr/bin/perl
use strict;
use DBI;

my $DB_HOST="127.0.0.1";
my $DB_PORT="3306";
my $DB_NAME="mydb";
my $DB_USER="test";
my $DB_PASS="test";

sub get_db_conn()
{
  my $dbh=undef;
  eval {
    $dbh = DBI->connect("dbi:mysql:dbname=$DB_NAME;host=$DB_HOST;port=$DB_PORT","$DB_USER","$DB_PASS");
  };
  if($@){
    print STDERR "DB ERROR $@n";
    $dbh = undef;
  }
  return $dbh;
}

my $dbh = get_db_conn();
my $sql = "select id, name from m_id";
my $sth = $dbh->prepare($sql);
$sth->execute();
print "Content-type: text/html;\n\n";
print "<html>";
print "<body>";
print "<table border=1>";
while(my $ary_ref = $sth->fetchrow_arrayref){
  my($id, $name) = @$ary_ref;
  print "<tr><td>$id</td><td>$name</td></tr>";
}
print "</table>";
print "</body>";
print "</html>";

 

■5. Confirmation

(5.1)start apache

apachectl start

(5.2)Access the following link.
http://localhost:8080/cgi-bin/test.cgi