diff --git a/Dockerfile b/Dockerfile index c1a72a1..649c285 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,15 +1,42 @@ -FROM mariadb:10.4 as database +FROM node:10-alpine as express LABEL Delirial elarcadeldelirio@gmail.com LABEL version="1.0" -LABEL description="API backend for testing and developed on Node+Express+Mongo. " -RUN apt-get update -RUN apt-get install nodejs npm -y -RUN node -v && npm -v -ENV MYSQL_ROOT_PASSWORD=1234 +LABEL description="API backend for testing and developed on Node+Express+Mariadb. " +RUN apk update --progress +RUN apk add -vv --progress mariadb mariadb-client +ENV DB_DATA_PATH="/var/lib/mysql" +ENV DB_ROOT_PASS="010495a" +ENV DB_USER="mariadb_user" +ENV DB_PASS="mariadb_user_password" +ENV MAX_ALLOWED_PACKET="200M" +ENV MYSQL_ROOT_PASSWORD=010495a +RUN ls /bin +ENV BASH_SOURCE=/usr/local/bin +COPY config/config-file.cnf /etc/mysql/my.cnf +RUN apk add openrc --no-cache +# #TODO: Add user to npm install +# RUN addgroup --gid "$NODE_GID" "$NODE_USER" \ +# && adduser \ +# --disabled-password \ +# --gecos "" \ +# --home /home/node \ +# --ingroup "$NODE_USER" \ +# --no-create-home \ +# --uid "$NODE_UID" \ +# "$NODE_USER" + +# Overwrite the default entrypoint of mariadb:10.4 +COPY init-docker.sh /usr/local/bin/ +RUN chmod +x /usr/local/bin/init-docker.sh +ENTRYPOINT ["/usr/local/bin/init-docker.sh"] +# Initializing a fresh instance +COPY db1-myment-backup-2019-07-29.sql /init-docker-initdb.d/db1-myment-backup-2019-07-29.sql WORKDIR /app COPY . . -RUN npm i +RUN chmod +x init-database.sh +# Change the permissions for security +COPY ./config/config-file.cnf /etc/mysql/conf.d +VOLUME ./data:/var/lib/mysql EXPOSE 5000 -EXPOSE 3306 -CMD ["npm","run","start"] +CMD ["mysqld_safe"] diff --git a/config/config-file.cnf b/config/config-file.cnf new file mode 100644 index 0000000..c4d3d9d --- /dev/null +++ b/config/config-file.cnf @@ -0,0 +1,183 @@ +# MariaDB database server configuration file. +# +# You can copy this file to one of: +# - "/etc/mysql/my.cnf" to set global options, +# - "~/.my.cnf" to set user-specific options. +# +# One can use all long options that the program supports. +# Run program with --help to get a list of available options and with +# --print-defaults to see which it would actually understand and use. +# +# For explanations see +# http://dev.mysql.com/doc/mysql/en/server-system-variables.html + +# This will be passed to all mysql clients +# It has been reported that passwords should be enclosed with ticks/quotes +# escpecially if they contain "#" chars... +# Remember to edit /etc/mysql/debian.cnf when changing the socket location. +[client] +port = 3306 +socket = /var/run/mysqld/mysqld.sock + +# Here is entries for some specific programs +# The following values assume you have at least 32M ram + +# This was formally known as [safe_mysqld]. Both versions are currently parsed. +[mysqld_safe] +socket = /var/run/mysqld/mysqld.sock +nice = 0 + +[mysqld] +# +# * Basic Settings +# +#user = mysql +pid-file = /var/run/mysqld/mysqld.pid +socket = /var/run/mysqld/mysqld.sock +port = 3306 +basedir = /usr +datadir = /var/lib/mysql +tmpdir = /tmp +lc_messages_dir = /usr/share/mysql +lc_messages = en_US +skip-external-locking +# +# Instead of skip-networking the default is now to listen only on +# localhost which is more compatible and is not less secure. +bind-address = 127.0.0.1 +# +# * Fine Tuning +# +max_connections = 100 +connect_timeout = 5 +wait_timeout = 600 +max_allowed_packet = 16M +thread_cache_size = 128 +sort_buffer_size = 4M +bulk_insert_buffer_size = 16M +tmp_table_size = 32M +max_heap_table_size = 32M +# +# * MyISAM +# +# This replaces the startup script and checks MyISAM tables if needed +# the first time they are touched. On error, make copy and try a repair. +myisam_recover_options = BACKUP +key_buffer_size = 128M +#open-files-limit = 2000 +table_open_cache = 400 +myisam_sort_buffer_size = 512M +concurrent_insert = 2 +read_buffer_size = 2M +read_rnd_buffer_size = 1M +# +# * Query Cache Configuration +# +# Cache only tiny result sets, so we can fit more in the query cache. +query_cache_limit = 128K +query_cache_size = 64M +# for more write intensive setups, set to DEMAND or OFF +#query_cache_type = DEMAND +# +# * Logging and Replication +# +# Both location gets rotated by the cronjob. +# Be aware that this log type is a performance killer. +# As of 5.1 you can enable the log at runtime! +#general_log_file = /var/log/mysql/mysql.log +#general_log = 1 +# +# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf. +# +# we do want to know about network errors and such +#log_warnings = 2 +# +# Enable the slow query log to see queries with especially long duration +#slow_query_log[={0|1}] +slow_query_log_file = /var/log/mysql/mariadb-slow.log +long_query_time = 10 +#log_slow_rate_limit = 1000 +#log_slow_verbosity = query_plan + +#log-queries-not-using-indexes +#log_slow_admin_statements +# +# The following can be used as easy to replay backup logs or for replication. +# note: if you are setting up a replication slave, see README.Debian about +# other settings you may need to change. +#server-id = 1 +#report_host = master1 +#auto_increment_increment = 2 +#auto_increment_offset = 1 +#log_bin = /var/log/mysql/mariadb-bin +#log_bin_index = /var/log/mysql/mariadb-bin.index +# not fab for performance, but safer +#sync_binlog = 1 +expire_logs_days = 10 +max_binlog_size = 100M +# slaves +#relay_log = /var/log/mysql/relay-bin +#relay_log_index = /var/log/mysql/relay-bin.index +#relay_log_info_file = /var/log/mysql/relay-bin.info +#log_slave_updates +#read_only +# +# If applications support it, this stricter sql_mode prevents some +# mistakes like inserting invalid dates etc. +#sql_mode = NO_ENGINE_SUBSTITUTION,TRADITIONAL +# +# * InnoDB +# +# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/. +# Read the manual for more InnoDB related options. There are many! +default_storage_engine = InnoDB +# you can't just change log file size, requires special procedure +#innodb_log_file_size = 50M +innodb_buffer_pool_size = 256M +innodb_log_buffer_size = 8M +innodb_file_per_table = 1 +innodb_open_files = 400 +innodb_io_capacity = 400 +innodb_flush_method = O_DIRECT +# +# * Security Features +# +# Read the manual, too, if you want chroot! +# chroot = /var/lib/mysql/ +# +# For generating SSL certificates I recommend the OpenSSL GUI "tinyca". +# +# ssl-ca=/etc/mysql/cacert.pem +# ssl-cert=/etc/mysql/server-cert.pem +# ssl-key=/etc/mysql/server-key.pem + +# +# * Galera-related settings +# +[galera] +# Mandatory settings +#wsrep_on=ON +#wsrep_provider= +#wsrep_cluster_address= +#binlog_format=row +#default_storage_engine=InnoDB +#innodb_autoinc_lock_mode=2 +# +# Allow server to accept connections on all interfaces. +# +bind-address=0.0.0.0 +# +# Optional setting +#wsrep_slave_threads=1 +#innodb_flush_log_at_trx_commit=0 + +[mysqldump] +quick +quote-names +max_allowed_packet = 16M + +[mysql] +#no-auto-rehash # faster start of mysql but no tab completion + +[isamchk] +key_buffer = 16M \ No newline at end of file diff --git a/config/database.js b/config/database.js index e77ec22..07795ea 100644 --- a/config/database.js +++ b/config/database.js @@ -1,6 +1,6 @@ const Sequelize = require('sequelize'); -module.exports = new Sequelize('myment', 'root', '010495a', { +module.exports = new Sequelize('mysql', 'root', '010495a', { host: 'localhost', dialect: 'mariadb', dialectOptions: { diff --git a/db1-myment-backup-2019-07-29.sql b/db1-myment-backup-2019-07-29.sql index 8be984a..9a79778 100644 --- a/db1-myment-backup-2019-07-29.sql +++ b/db1-myment-backup-2019-07-29.sql @@ -15,6 +15,9 @@ /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; +DROP DATABASE IF EXISTS myment; +CREATE DATABASE myment; +USE myment; -- -- Table structure for table `add` -- diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100644 index 0000000..2f466e7 --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,174 @@ +#!/bin/bash +set -eo pipefail +shopt -s nullglob + +if [[ $(whoami) == 'root' ]]; then + whoami + echo + echo 'Initializate express app' + echo + npm ci --only=prod --loglevel=verbose +fi +# if command starts with an option, prepend mysqld +echo "$1" +echo "$2" +echo "$3" +if [ "${1:0:1}" = '-' ]; then + echo "$@" +fi + +whoami && id +echo "$@" +_check_config() { + toRun=( mysqld --verbose --help --log-bin-index="$(mktemp -u)" ) + if ! errors="$("${toRun[@]}" 2>&1 >/dev/null)"; then + cat >&2 <<-EOM + + ERROR: mysqld failed while attempting to check config + command was: "${toRun[*]}" + + $errors + EOM + exit 1 + fi +} + +# Fetch value from server config +# We use mysqld --verbose --help instead of my_print_defaults because the +# latter only show values present in config files, and not server defaults +_get_config() { + local conf="$1"; shift + mysqld --verbose --help --log-bin-index="$(mktemp -u)" 2>/dev/null \ + | awk '$1 == "'"$conf"'" && /^[^ \t]/ { sub(/^[^ \t]+[ \t]+/, ""); print; exit }' + # match "datadir /some/path with/spaces in/it here" but not "--xyz=abc\n datadir (xyz)" +} + +# allow the container to be started with `--user` +if [ "$(id -u)" = '0' ]; then + _check_config "mysqld" + DATADIR="$(_get_config 'datadir' "mysqld")" + mkdir -p "$DATADIR" + find "$DATADIR" \! -user mysql -exec chown mysql '{}' + + #TODO use less protective su command + su mysql "$BASH_SOURCE" "mysqld" + exec gosu mysql "$BASH_SOURCE" "mysqld" +fi + + +# still need to check config, container may have started with --user +_check_config mysqld +# Get config +DATADIR="$(_get_config 'datadir' mysqld)" + +if [ ! -d "$DATADIR/mysql" ]; then + if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then + echo >&2 'error: database is uninitialized and password option is not specified ' + echo >&2 ' You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD' + exit 1 + fi + + mkdir -p "$DATADIR" + + echo 'Initializing database' + installArgs=( --datadir="$DATADIR" --rpm ) + if { mysql_install_db --help || :; } | grep -q -- '--auth-root-authentication-method'; then + # beginning in 10.4.3, install_db uses "socket" which only allows system user root to connect, switch back to "normal" to allow mysql root without a password + # see https://github.com/MariaDB/server/commit/b9f3f06857ac6f9105dc65caae19782f09b47fb3 + # (this flag doesn't exist in 10.0 and below) + installArgs+=( --auth-root-authentication-method=normal ) + fi + # "Other options are passed to mysqld." (so we pass all "mysqld" arguments directly here) + mysql_install_db "${installArgs[@]}" "${@:2}" + echo 'Database initialized' + + SOCKET="$(_get_config 'socket' mysqld)" + mysqld --skip-networking --socket="${SOCKET}" & + pid="$!" + + mysql=( mysql --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" ) + + for i in {30..0}; do + if echo 'SELECT 1' | "${mysql[@]}" &> /dev/null; then + break + fi + echo 'MySQL init process in progress...' + sleep 1 + done + if [ "$i" = 0 ]; then + echo >&2 'MySQL init process failed.' + exit 1 + fi + + if [ -z "$MYSQL_INITDB_SKIP_TZINFO" ]; then + # sed is for https://bugs.mysql.com/bug.php?id=20545 + mysql_tzinfo_to_sql /usr/share/zoneinfo | sed 's/Local time zone must be set--see zic manual page/FCTY/' | "${mysql[@]}" mysql + fi + + if [ ! -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then + export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)" + echo "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD" + fi + + rootCreate= + # default root to listen for connections from anywhere + if [ ! -z "$MYSQL_ROOT_HOST" -a "$MYSQL_ROOT_HOST" != 'localhost' ]; then + # no, we don't care if read finds a terminating character in this heredoc + # https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151 + read -r -d '' rootCreate <<-EOSQL || true + CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ; + GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ; +EOSQL + fi + + "${mysql[@]}" <<-EOSQL + -- What's done in this file shouldn't be replicated + -- or products like mysql-fabric won't work + SET @@SESSION.SQL_LOG_BIN=0; + + DELETE FROM mysql.user WHERE user NOT IN ('mysql.sys', 'mysqlxsys', 'root') OR host NOT IN ('localhost') ; + SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ; + GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ; + ${rootCreate} + DROP DATABASE IF EXISTS test ; + FLUSH PRIVILEGES ; +EOSQL + + if [ ! -z "$MYSQL_ROOT_PASSWORD" ]; then + mysql+=( -p"${MYSQL_ROOT_PASSWORD}" ) + fi + + if [ "$MYSQL_DATABASE" ]; then + echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" | "${mysql[@]}" + mysql+=( "$MYSQL_DATABASE" ) + fi + + + if [ "$MYSQL_USER" -a "$MYSQL_PASSWORD" ]; then + echo "CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ;" | "${mysql[@]}" + + if [ "$MYSQL_DATABASE" ]; then + echo "GRANT ALL ON \`$MYSQL_DATABASE\`.* TO '$MYSQL_USER'@'%' ;" | "${mysql[@]}" + fi + fi + + echo + for f in /docker-entrypoint-initdb.d/*; do + case "$f" in + *.sh) echo "$0: running $f"; . "$f" ;; + *.sql) echo "$0: running $f"; "${mysql[@]}" < "$f"; echo ;; + *.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${mysql[@]}"; echo ;; + *) echo "$0: ignoring $f" ;; + esac + echo + done + + if ! kill -s TERM "$pid" || ! wait "$pid"; then + echo >&2 'MySQL init process failed.' + exit 1 + fi + + echo + echo 'MySQL init process done. Ready for start up.' + echo + echo +fi diff --git a/init-database.sh b/init-database.sh new file mode 100644 index 0000000..f2d7ae2 --- /dev/null +++ b/init-database.sh @@ -0,0 +1,12 @@ +#!/bin/sh +mysqladmin -u root password "${DB_ROOT_PASS}" +echo "GRANT ALL ON *.* TO ${DB_USER}@'127.0.0.1' IDENTIFIED BY '${DB_PASS}' WITH GRANT OPTION;" > /tmp/sql +echo "GRANT ALL ON *.* TO ${DB_USER}@'localhost' IDENTIFIED BY '${DB_PASS}' WITH GRANT OPTION;" >> /tmp/sql +echo "GRANT ALL ON *.* TO ${DB_USER}@'::1' IDENTIFIED BY '${DB_PASS}' WITH GRANT OPTION;" >> /tmp/sql +echo "DELETE FROM mysql.user WHERE User='';" >> /tmp/sql +echo "DROP DATABASE test;" >> /tmp/sql +echo "FLUSH PRIVILEGES;" >> /tmp/sql +cat /tmp/sql | mysql -u root --password="${DB_ROOT_PASS}" +rm /tmp/sql +sed -i "s|max_allowed_packet\s*=\s*1M|max_allowed_packet = ${MAX_ALLOWED_PACKET}|g" /etc/mysql/my.cnf +sed -i "s|max_allowed_packet\s*=\s*16M|max_allowed_packet = ${MAX_ALLOWED_PACKET}|g" /etc/mysql/my.cnf \ No newline at end of file diff --git a/init-docker.sh b/init-docker.sh new file mode 100644 index 0000000..cd85227 --- /dev/null +++ b/init-docker.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -e + +if [[ $(id -u) = 0 ]]; then + mysql_install_db --user=mysql --datadir=${DB_DATA_PATH} + echo + echo 'Initializate express app' + echo + npm i --only=prod --loglevel=verbose +fi +exec "$@" \ No newline at end of file diff --git a/package.json b/package.json index 6529af4..eac0e67 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "This repo contain the back API for the web application myment.", "main": "index.js", "scripts": { - "start": "mysqld && node app.js", + "start": "sh init-database.sh && node app.js", "dev": "nodemon app.js" }, "keywords": [], @@ -20,24 +20,22 @@ "homepage": "https://github.com/fullstacktf/myment-back#readme", "dependencies": { "express": "^4.17.1", - "typescript": "^3.5.2", "express-handlebars": "^3.1.0", "mariadb": "^2.1.0", "sequelize": "^5.10.3" }, "devDependencies": { + "typescript": "^3.5.2", + "eslint": "^6.0.1", + "eslint-config-prettier": "^6.0.0", + "eslint-plugin-jest": "^22.7.2", + "eslint-plugin-prettier": "^3.1.0", "@types/body-parser": "^1.17.0", "@types/express": "^4.17.0", "@types/jest": "^24.0.15", - "@types/mongoose": "^5.5.7", "@types/node": "^12.0.12", "@typescript-eslint/eslint-plugin": "^1.11.0", "@typescript-eslint/parser": "^1.11.0", - "eslint": "^6.0.1", - "eslint-config-prettier": "^6.0.0", - "eslint-plugin-jest": "^22.7.2", - "eslint-plugin-prettier": "^3.1.0", - "express-generator": "^4.16.1", "jest": "^24.8.0", "prettier": "^1.18.2", "ts-jest": "^24.0.2",