20210511のMySQLに関する記事は8件です。

UNION ALL

UNION ALLとは クエリの結果を一緒にするために使う。 具体例 データ こういうデータがあったとする。 +----+------+------+------+ | id | x | y | z | +----+------+------+------+ | 1 | 1 | 2 | 3 | | 2 | 5 | 5 | 2 | | 3 | 4 | 7 | 1 | | 4 | 3 | 3 | 8 | +----+------+------+------+ SQL発行 idと(x,y,z)カラムをtablesテーブルからSELECTする。 SELECT id, x AS value FROM tables UNION ALL SELECT id, y AS value FROM tables UNION ALL SELECT id, z AS value FROM tables クエリ結果 3つのSELECTの結果がくっついてることがわかる。 +----+------+ | id | col | +----+------+ | 1 | 1 | | 2 | 5 | | 3 | 4 | | 4 | 3 | | 1 | 2 | | 2 | 5 | | 3 | 7 | | 4 | 3 | | 1 | 3 | | 2 | 2 | | 3 | 1 | | 4 | 8 | +----+------+ 周辺 UNIONとUNION ALLの違い 挙動 UNIONは重複しているものが削除されます。 以下、UNIONで発行した結果ですが、(id, col)の組み合わせで重複しているものが排除されています。 +----+------+ | id | col | +----+------+ | 1 | 1 | | 2 | 5 | | 3 | 4 | | 4 | 3 | | 1 | 2 | | 3 | 7 | | 1 | 3 | | 2 | 2 | | 3 | 1 | | 4 | 8 | +----+------+ パフォーマンス ユニークである挙動を持っているため、UNIONの方が重いらしいです。 注意点 上の例だと、x,y,zはいずれも整数型であり揃ってますね 同じテーブルの似たようなカラムなので条件は満たしていそうです。 なお、型に関しては暗黙的に変換できるものなら大丈夫だそう。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

rails (apiモード)+ Docker + mysql 環境構築(メモ)

はじめに 学習したことのメモとして書いていきます。 ディレクトリ構造 api/  ├ Gemfile  ├ Gemfile.lock  ├ Dockerfile  ├ docker-compose.yml  ├ entrypoint.sh  Dockerfile dockercompose.yml Gemfile entrypoint.sh Dockerfile FROM ruby:2.7.3-buster RUN apt-get update #最新版のyarnをインストールできるように設定 RUN set -x && curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \ echo 'deb http://dl.yarnpkg.com/debian/ stable main' > /etc/apt/sources.list.d/yarn.list #nodeのバージョンを指定 RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - && \ apt-get install nodejs RUN apt-get install -y \ build-essential \ libpq-dev \ nodejs \ yarn RUN mkdir /api WORKDIR /api COPY Gemfile /api/ COPY Gemfile.lock /api/ RUN bundle install COPY entrypoint.sh /usr/bin/ #entrypoint.shの権限を付与 RUN chmod +x /usr/bin/entrypoint.sh #entrypoint.shを毎回実行 ENTRYPOINT ["entrypoint.sh"] #ポートを3000にする EXPOSE 3000 CMD ["rails", "server", "-b", "0.0.0.0"] docker-compose.yml version: '3' volumes: db-data: api: build: context: . dockerfile: Dockerfile volumes: - './api:/api' ports: - '8000:3000' tty: true stdin_open: true depends_on: - db links: - db db: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: root ports: - '3306:3306' volumes: db-data: でdockervolumeを作成してコンテナ内のデータベースにマウント。詳しくはこちらのブログ。 volumeの場所についてはこちら entrypoint.sh #!/bin/bash set -e # Remove a potentially pre-existing server.pid for Rails. rm -f /myapp/tmp/pids/server.pid # Then exec the container's main process (what's set as CMD in the Dockerfile). exec "$@" Gemfile source 'https://rubygems.org' gem 'rails', '~>6' docker-compose run の実行 この状態でdocker-compose upしてもわたしコンテナはアクティブになりませんでした。 次にコマンドを実行します docker-compose run api rails new . --api --force --database=mysql --skip-bundle --skip-test --skip-bundle : Dockerfileでbundle install するのでbundleをスキップ --force : rails new で作られるファイルがすでに存在する場合上書き --skip-test : rspecを使うのでスキップ この後 docker-compose up を実行します。 database.ymlの編集 またdatabase.ymlのデフォルトの部分を以下のように編集する datbase.yml default: &default adapter: mysql2 encoding: utf8mb4 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> username: root password: password host: db 最後にコンテナ内でrails db:create これでdocker-compose up を行った後、指定したポート(今回は8000)でURL(localhost:8000)を入力すればよく見るrails の画面が現れる。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

TypeORMを用いてMySQLとNestJSの接続時にエラーが出た場合 ERROR 1045(28000)

備忘録のために 使用したもの VSCode TypeORM NestJS MySQL ①NestJSのインストール npm i -g @nestjs/cli ②MySQLとTypeORMのインストール npm install --save @nestjs/typeorm typeorm mysql2 ここまでは公式と同じ 参考ページ:https://docs.nestjs.com/techniques/database 諸々設定してlocalhost繋ごうとしたら以下のエラー ERROR 1045 (28000): Access denied for user...//以下省略 色々調べた結果 mysqld_safe --skip-grant-tables & を入力するとエラーが出ずに進んだ 続いて、下記のものを入力すると mysql -u root -p Enter password: が出てきてパスワードを入力するとMySQLにログインできた 参考文献 https://qiita.com/ponsuke0531/items/df51a784b5ff48c97ac7
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

dockerでsymfony & mysql & phpmyAdminのローカル開発環境を作る。

概要 dockerでsymfonyの構築ができたので、動いた時点のファイルをメモしています。 このページは参考ページをもとにしているため、合わせて読むとわかりやすいです。 環境 M1チップMac BigSur 2021/5/11時点で動作。 前提 Docker-syncがインストールされている。 まだの場合、一番下の参考ページにコマンドがあるのでコピペして実行してください。 Dockerは知っている。 コンテナ、イメージ、ボリュームは知っている。 apacheのconfや.htaccessはどういうものかわかる。 MAMPや簡易サーバでなら構築できる。 Linuxの基本はわかる。 参考ページと同じディレクトリ構成を作る。 任意の空のフォルダに移動して、下記のコマンド。 touch create_docker_dir.sh できたファイルに以下をコピペ。 docker-sync.yaml だと この後の工程でエラーになったので拡張子に注意(aが余分)。 docker-comopseは逆にyamlなので紛らわしいです。 また、DockerfileはDockerFileとかくとエラーになります。 ハマるポイントが多いので手でタイプするのはやめた方がいいです。 create_docker_dir.sh #!/bin/bash mkdir app mkdir -p docker/apache docker/php touch docker/apache/my_app.conf touch docker/php/php.ini touch docker/Dockerfile touch .env docker-compose.yaml docker-sync.yml シェルを実行。 sh create_docker_dir.sh DockerFileにコピペする。 DockerFileの内容 参考ページのままだとドライバがないというエラーが起きた。 MySQLを使う場合は以下を追記。 なぜか書かないとsqlLigteのドライバしかない。 他は丸写しだったと思う。 RUN docker-php-ext-install pdo_mysql mysqli ./docker/DockerFile FROM php:7.4-apache RUN cd /etc/apache2/mods-enabled \ && ln -s ../mods-available/rewrite.load RUN a2dissite 000-default WORKDIR /var/www/html RUN apt-get update && apt-get install -y git zip unzip RUN apt-get install -y wget libjpeg-dev libfreetype6-dev RUN apt-get install -y libmagick++-dev \ libmagickwand-dev \ libpq-dev \ libfreetype6-dev \ libjpeg62-turbo-dev \ libpng-dev \ libwebp-dev \ libxpm-dev RUN docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ RUN docker-php-ext-install -j$(nproc) gd RUN docker-php-ext-install pdo_mysql mysqli RUN cd /usr/bin && curl -s http://getcomposer.org/installer | php && mv /usr/bin/composer.phar /usr/bin/composer docker-composeにコピペする ./docker-comose.yml version: '3' volumes: mysql-database: driver: local my_app_symfony: external: true services: app: container_name: my_app build: ./docker ports: - 8901:80 volumes: - my_app_symfony:/var/www/html - ./docker/php/php.ini:/usr/local/etc/php/php.ini - ./docker/apache/my_app.conf:/etc/apache2/sites-enabled/my_app.conf depends_on: - mysql environment: DATABASE_URL: "mysql://root:root@mysql/app_db" DATABASE_SERVER_VERSION: 10 mysql: image: mysql:5.7 container_name: my_app_app_mysql environment: MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD MYSQL_DATABASE: $DB_NAME TZ: 'Asia/Tokyo' command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci ports: - 13306:3306 platform: linux/x86_64 volumes: - mysql-database:/var/lib/mysql phpmyadmin: image: phpmyadmin/phpmyadmin environment: - PMA_ARBITRARY=1 - PMA_HOST=mysql - PMA_USER=root - PMA_PASSWORD=$DB_ROOT_PASSWORD links: - mysql ports: - 8902:80 volumes: - /sessions docker-syncにコピペする my_app_symfonyの部分は、プロジェクトごとに別の名前をつけないと同じソースコードを参照してしまうので注意。 変更した場合、docker-composeも同じ名前に揃える。 ./docker-sync.yml version: '2' syncs: my_app_symfony: src: './app' sync_host_ip: '127.0.0.1' sync_host_port: '5000' sync_strategy: 'native_osx' sync_excludes: ['.git', '.gitignore', 'node_modules'] .envにコピペする ./.env DB_ROOT_PASSWORD=root DB_NAME=app_db my_app.confにコピペする 参考ページからDirectoryタグの中を追記しました。 公開ディレクトリにAllowOverride Allの記述がないとSymfonyのルーティングが弾かれます。 対象フォルダの.htaccessを有効化する記述みたいです。 ./docker/apache/my_app.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html/my_app/public ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <Directory /var/www/html/my_app/public> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> php.iniにコピペする ./docker/php/php.ini memory_limit = 2048M date.timezone = "Asia/Tokyo" mbstring.internal_encoding = "UTF-8" mbstring.language = "Japanese" docker-syncを起動する コンテナから切り離して永続させるフォルダをマウントする。 docker-sync start success Sync container started success Starting Docker-Sync in the background が出て、 .docker-syncディレクトリが新たに出現していたら成功。 コンテナを立ち上げる -d をつけるとバックで処理してくれる。 --build をつけるとDockerFileをコンパイルしてimageを生成しなおす(多分)。 なのでDockerFileを編集したら--buildオプションをつける。 止めるときはdocker-compose down docker-compose up -d --build この時点でこうなっている。 appフォルダの中はまだ空。 Symfonyをインストール コンテナの中に入る symfony/skeletonだとweb関連のファイルがインストールされない。 docker-compose exec app /bin/bash composer create-project symfony/website-skeleton my_app 今、こうなっている。 /app配下がsymfonyプロジェクトになっているようです。 アクセスする。 ここまで合っていれば、以下のページが表示されるはず。 symfony http://localhost:8901/ phpMyAdmin http://localhost:8902/ Symfonyからルーティングできるようにする。 このままの状態では、welcomeページしか表示できません。 他のページにアクセスすると全て404 not found エラーでapacheに弾かれます。 そこでプロジェクトフォルダのpublicフォルダ内に.htaccessを置いて許可設定を記述します。 cd ./app/my_app/public touch .htaccess できたファイルに以下をコピペする。 何か専用のコマンドを打つとできたような気がしますけど、どこで見たか忘れました。 自分で貼り付けても動いているので問題ないと思います。 ./app/my_app/public/.htaccess # Use the front controller as index file. It serves as a fallback solution when # every other rewrite/redirect fails (e.g. in an aliased environment without # mod_rewrite). Additionally, this reduces the matching process for the # start page (path "/") because otherwise Apache will apply the rewriting rules # to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl). DirectoryIndex index.php # By default, Apache does not evaluate symbolic links if you did not enable this # feature in your server configuration. Uncomment the following line if you # install assets as symlinks or if you experience problems related to symlinks # when compiling LESS/Sass/CoffeScript assets. # Options +FollowSymlinks # Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve # to the front controller "/index.php" but be rewritten to "/index.php/index". <IfModule mod_negotiation.c> Options -MultiViews </IfModule> <IfModule mod_rewrite.c> RewriteEngine On # Determine the RewriteBase automatically and set it as environment variable. # If you are using Apache aliases to do mass virtual hosting or installed the # project in a subdirectory, the base path will be prepended to allow proper # resolution of the index.php file and to redirect to the correct URI. It will # work in environments without path prefix as well, providing a safe, one-size # fits all solution. But as you do not need it in this case, you can comment # the following 2 lines to eliminate the overhead. RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$ RewriteRule .* - [E=BASE:%1] # Sets the HTTP_AUTHORIZATION header removed by Apache RewriteCond %{HTTP:Authorization} .+ RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0] # Redirect to URI without front controller to prevent duplicate content # (with and without `/index.php`). Only do this redirect on the initial # rewrite by Apache and not on subsequent cycles. Otherwise we would get an # endless redirect loop (request -> rewrite to front controller -> # redirect -> request -> ...). # So in case you get a "too many redirects" error or you always get redirected # to the start page because your Apache does not expose the REDIRECT_STATUS # environment variable, you have 2 choices: # - disable this feature by commenting the following 2 lines or # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the # following RewriteCond (best solution) RewriteCond %{ENV:REDIRECT_STATUS} ="" RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L] # If the requested filename exists, simply serve it. # We only want to let Apache serve files and not directories. # Rewrite all other queries to the front controller. RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ %{ENV:BASE}/index.php [L] </IfModule> <IfModule !mod_rewrite.c> <IfModule mod_alias.c> # When mod_rewrite is not available, we instruct a temporary redirect of # the start page to the front controller explicitly so that the website # and the generated links can still be used. RedirectMatch 307 ^/$ /index.php/ # RedirectTemp cannot be used instead </IfModule> </IfModule> トップページ以外アクセスできるか試す。 テストコントローラを作る。symfonyはアノテーションでルーティングできるので同時にルートが生成されている。 cd ./my_app/ php bin/console make:controller HelloController ここで、composerのphpバージョンが古いというようなエラーが出ました。 以下のコマンドを打ってからもう一度make:controllerしたら動きました。 composer update symfony側からルーティングできているか確認。 php bin/console debug:route apacheにブロックされないことを確認する。 http://localhost:8901/hello 以上 お疲れ様でした。 参考 主に以下のページをもとに、自分の環境で動かなかったところを編集しました。 他にも色々なページをググりまくりましたが、どれをどこでみたか覚えていません。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

dockerでsymfony & mysql & phpmyAdminのローカル開発環境を作る。①

概要 dockerでsymfonyの構築ができたので、動いた時点のファイルをメモしています。 このページは参考ページをもとにしているため、合わせて読むとわかりやすいです。 環境 M1チップMac BigSur 2021/5/11時点で動作。 前提 Docker-syncがインストールされている。 まだの場合、一番下の参考ページにコマンドがあるのでコピペして実行してください。 Dockerは知っている。 コンテナ、イメージ、ボリュームは知っている。 apacheのconfや.htaccessはどういうものかわかる。 MAMPや簡易サーバでなら構築できる。 Linuxの基本はわかる。 参考ページと同じディレクトリ構成を作る。 任意の空のフォルダに移動して、下記のコマンド。 touch create_docker_dir.sh できたファイルに以下をコピペ。 docker-sync.yaml だと この後の工程でエラーになったので拡張子に注意(aが余分)。 docker-comopseは逆にyamlなので紛らわしいです。 また、DockerfileはDockerFileとかくとエラーになります。 ハマるポイントが多いので手でタイプするのはやめた方がいいです。 create_docker_dir.sh #!/bin/bash mkdir app mkdir -p docker/apache docker/php touch docker/apache/my_app.conf touch docker/php/php.ini touch docker/Dockerfile touch .env docker-compose.yaml docker-sync.yml シェルを実行。 sh create_docker_dir.sh DockerFileにコピペする。 DockerFileの内容 参考ページのままだとドライバがないというエラーが起きた。 MySQLを使う場合は以下を追記。 なぜか書かないとsqlLigteのドライバしかない。 他は丸写しだったと思う。 RUN docker-php-ext-install pdo_mysql mysqli ./docker/DockerFile FROM php:7.4-apache RUN cd /etc/apache2/mods-enabled \ && ln -s ../mods-available/rewrite.load RUN a2dissite 000-default WORKDIR /var/www/html RUN apt-get update && apt-get install -y git zip unzip RUN apt-get install -y wget libjpeg-dev libfreetype6-dev RUN apt-get install -y libmagick++-dev \ libmagickwand-dev \ libpq-dev \ libfreetype6-dev \ libjpeg62-turbo-dev \ libpng-dev \ libwebp-dev \ libxpm-dev RUN docker-php-ext-configure gd --with-freetype=/usr/include/ --with-jpeg=/usr/include/ RUN docker-php-ext-install -j$(nproc) gd RUN docker-php-ext-install pdo_mysql mysqli RUN cd /usr/bin && curl -s http://getcomposer.org/installer | php && mv /usr/bin/composer.phar /usr/bin/composer docker-composeにコピペする ./docker-comose.yml version: '3' volumes: mysql-database: driver: local my_app_symfony: external: true services: app: container_name: my_app build: ./docker ports: - 8901:80 volumes: - my_app_symfony:/var/www/html - ./docker/php/php.ini:/usr/local/etc/php/php.ini - ./docker/apache/my_app.conf:/etc/apache2/sites-enabled/my_app.conf depends_on: - mysql environment: DATABASE_URL: "mysql://root:root@mysql/app_db" DATABASE_SERVER_VERSION: 10 mysql: image: mysql:5.7 container_name: my_app_app_mysql environment: MYSQL_ROOT_PASSWORD: $DB_ROOT_PASSWORD MYSQL_DATABASE: $DB_NAME TZ: 'Asia/Tokyo' command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci ports: - 13306:3306 platform: linux/x86_64 volumes: - mysql-database:/var/lib/mysql phpmyadmin: image: phpmyadmin/phpmyadmin environment: - PMA_ARBITRARY=1 - PMA_HOST=mysql - PMA_USER=root - PMA_PASSWORD=$DB_ROOT_PASSWORD links: - mysql ports: - 8902:80 volumes: - /sessions docker-syncにコピペする my_app_symfonyの部分は、プロジェクトごとに別の名前をつけないと同じソースコードを参照してしまうので注意。 変更した場合、docker-composeも同じ名前に揃える。 ./docker-sync.yml version: '2' syncs: my_app_symfony: src: './app' sync_host_ip: '127.0.0.1' sync_host_port: '5000' sync_strategy: 'native_osx' sync_excludes: ['.git', '.gitignore', 'node_modules'] .envにコピペする ./.env DB_ROOT_PASSWORD=root DB_NAME=app_db my_app.confにコピペする 参考ページからDirectoryタグの中を追記しました。 公開ディレクトリにAllowOverride Allの記述がないとSymfonyのルーティングが弾かれます。 対象フォルダの.htaccessを有効化する記述みたいです。 ./docker/apache/my_app.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html/my_app/public ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> <Directory /var/www/html/my_app/public> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> php.iniにコピペする ./docker/php/php.ini memory_limit = 2048M date.timezone = "Asia/Tokyo" mbstring.internal_encoding = "UTF-8" mbstring.language = "Japanese" docker-syncを起動する コンテナから切り離して永続させるフォルダをマウントする。 docker-sync start success Sync container started success Starting Docker-Sync in the background が出て、 .docker-syncディレクトリが新たに出現していたら成功。 コンテナを立ち上げる -d をつけるとバックで処理してくれる。 --build をつけるとDockerFileをコンパイルしてimageを生成しなおす(多分)。 なのでDockerFileを編集したら--buildオプションをつける。 止めるときはdocker-compose down docker-compose up -d --build この時点でこうなっている。 appフォルダの中はまだ空。 Symfonyをインストール コンテナの中に入る symfony/skeletonだとweb関連のファイルがインストールされない。 docker-compose exec app /bin/bash composer create-project symfony/website-skeleton my_app 今、こうなっている。 /app配下がsymfonyプロジェクトになっているようです。 アクセスする。 ここまで合っていれば、以下のページが表示されるはず。 symfony http://localhost:8901/ phpMyAdmin http://localhost:8902/ Symfonyからルーティングできるようにする。 このままの状態では、welcomeページしか表示できません。 他のページにアクセスすると全て404 not found エラーでapacheに弾かれます。 そこでプロジェクトフォルダのpublicフォルダ内に.htaccessを置いて許可設定を記述します。 cd ./app/my_app/public touch .htaccess できたファイルに以下をコピペする。 何か専用のコマンドを打つとできたような気がしますけど、どこで見たか忘れました。 自分で貼り付けても動いているので問題ないと思います。 ./app/my_app/public/.htaccess # Use the front controller as index file. It serves as a fallback solution when # every other rewrite/redirect fails (e.g. in an aliased environment without # mod_rewrite). Additionally, this reduces the matching process for the # start page (path "/") because otherwise Apache will apply the rewriting rules # to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl). DirectoryIndex index.php # By default, Apache does not evaluate symbolic links if you did not enable this # feature in your server configuration. Uncomment the following line if you # install assets as symlinks or if you experience problems related to symlinks # when compiling LESS/Sass/CoffeScript assets. # Options +FollowSymlinks # Disabling MultiViews prevents unwanted negotiation, e.g. "/index" should not resolve # to the front controller "/index.php" but be rewritten to "/index.php/index". <IfModule mod_negotiation.c> Options -MultiViews </IfModule> <IfModule mod_rewrite.c> RewriteEngine On # Determine the RewriteBase automatically and set it as environment variable. # If you are using Apache aliases to do mass virtual hosting or installed the # project in a subdirectory, the base path will be prepended to allow proper # resolution of the index.php file and to redirect to the correct URI. It will # work in environments without path prefix as well, providing a safe, one-size # fits all solution. But as you do not need it in this case, you can comment # the following 2 lines to eliminate the overhead. RewriteCond %{REQUEST_URI}::$0 ^(/.+)/(.*)::\2$ RewriteRule .* - [E=BASE:%1] # Sets the HTTP_AUTHORIZATION header removed by Apache RewriteCond %{HTTP:Authorization} .+ RewriteRule ^ - [E=HTTP_AUTHORIZATION:%0] # Redirect to URI without front controller to prevent duplicate content # (with and without `/index.php`). Only do this redirect on the initial # rewrite by Apache and not on subsequent cycles. Otherwise we would get an # endless redirect loop (request -> rewrite to front controller -> # redirect -> request -> ...). # So in case you get a "too many redirects" error or you always get redirected # to the start page because your Apache does not expose the REDIRECT_STATUS # environment variable, you have 2 choices: # - disable this feature by commenting the following 2 lines or # - use Apache >= 2.3.9 and replace all L flags by END flags and remove the # following RewriteCond (best solution) RewriteCond %{ENV:REDIRECT_STATUS} ="" RewriteRule ^index\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L] # If the requested filename exists, simply serve it. # We only want to let Apache serve files and not directories. # Rewrite all other queries to the front controller. RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ %{ENV:BASE}/index.php [L] </IfModule> <IfModule !mod_rewrite.c> <IfModule mod_alias.c> # When mod_rewrite is not available, we instruct a temporary redirect of # the start page to the front controller explicitly so that the website # and the generated links can still be used. RedirectMatch 307 ^/$ /index.php/ # RedirectTemp cannot be used instead </IfModule> </IfModule> トップページ以外アクセスできるか試す。 テストコントローラを作る。symfonyはアノテーションでルーティングできるので同時にルートが生成されている。 cd ./my_app/ php bin/console make:controller HelloController ここで、composerのphpバージョンが古いというようなエラーが出ました。 以下のコマンドを打ってからもう一度make:controllerしたら動きました。 composer update symfony側からルーティングできているか確認。 php bin/console debug:route apacheにブロックされないことを確認する。 http://localhost:8901/hello 続き この後、symfonyでエンティティ作ってマイグレーションしたらエラーでつまづいたので、 その対処法を以下に書きました。 参考 主に以下のページをもとに、自分の環境で動かなかったところを編集しました。 他にも色々なページをググりまくりましたが、どれをどこでみたか覚えていません。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MySQLのタイムゾーンを日本時間にする(Ubuntu18.04)

勘違いしていたこと MySQLのタイムゾーンはデフォルトでホストマシンのタイムゾーンを参照している! ❎my.cnfを編集する ?Ubuntuのタイムゾーンを変更する ホストマシン(Ubuntu)のタイムゾーンを変更 $> date Tue May 11 07:43:16 UTC 2021 日時を確認 UTCからJSTに変える $> timedatectl set-timezone Asia/Tokyo ==== AUTHENTICATING FOR org.freedesktop.timedate1.set-timezone === Authentication is required to set the system timezone. Authenticating as: vagrant,,, (vagrant) Password: パスワードを入力 ==== AUTHENTICATION COMPLETE === と出たら成功 $> date Tue May 11 16:44:02 JST 2021 JSTになってることを確認 MySQLを確認 MySQLに接続し確認 mysql> show variables like '%time_zone%'; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | UTC | | time_zone | SYSTEM | +------------------+--------+ 2 rows in set (0.01 sec) あれ?変わってない。。。 MySQLを再起動 mysql> exit Bye $> systemctl restart mysql ==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units === Authentication is required to restart 'mysql.service'. Authenticating as: vagrant,,, (vagrant) Password: ==== AUTHENTICATION COMPLETE === mysql> show variables like '%time_zone%'; +------------------+--------+ | Variable_name | Value | +------------------+--------+ | system_time_zone | JST | | time_zone | SYSTEM | +------------------+--------+ 2 rows in set (0.00 sec) 行けた! MySQL再起動することをお忘れなく〜
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

mySQLが起動しなくなった!!

こんにちは! 今朝PHPの環境を構築していたところ、 mySQLが起動しなくなった!!!というトラブルが発生し、色々と調べて解決しましたので その記録を残しておこうと思います なんでもこの起動エラー、皆様にも発生する可能性が十分にあり得ますので 発生しても焦らないでくださいね 発生エラー % mysql -u root ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (38) mysqlに接続できなくなりました。 '/tmp/mysql.sock'を通じてローカルmysqlサーバーに接続できなかったよ という日本語訳になります。 環境 homebrewインストール済み macOS Big Sur ver.11.2.3 ネットで様々調べていると、ここでいきなり解決に走る記事が多いですが、 念の為現状を確認をしておきましょう 確認なので、エラーが出て当然です 現状確認 % sudo mysql.server restart # 再起動してみる ERROR! MySQL server PID file could not be found! Starting MySQL.... ERROR! The server quit without updating PID file (/usr/local/var/mysql/itoutakahironoMacBook-Pro.local.pid). % ps aux | grep mysql # mysqlが動いているか確認する(プロセスの確認) zsh: bus error ps aux | zsh: exit 1 grep mysql % brew doctor # brewの一般的な問題をチェック Warning: Some installed formulae are deprecated or disabled. You should find replacements for the following formulae: ilmbase mysql@5.6 Warning: "config" scripts exist outside your system or Homebrew directories. `./configure` scripts often look for *-config scripts to determine if software packages are installed, and which additional flags to use when compiling and linking. Warning: You have unlinked kegs in your Cellar. Leaving kegs unlinked can lead to build-trouble and cause formulae that depend on those kegs to fail to run properly once built. Run `brew link` on these: imath openexr Warning: Broken symlinks were found. Remove them with `brew cleanup`: /usr/local/share/man/man5/package-locks.5 /usr/local/share/man/man5/shrinkwrap-json.5 一旦、記憶も整理しておきましょう # 何か設定を変更した記憶はあるか → ない # アップグレードした記憶はあるか → 今朝PHPのインストールをした際に動いてしまったかも… 大事なことは、自分で何か触った記憶はあるかという点だけにしておきます笑 色々と設定をイジる解決方法が見つかりますが、そもそも触ってないんだからここは間違ってないのでは?? という私の見解です では、mySQLをもう一度見ていきます # mySQLのバージョンを確認する % cd /tmp/ % brew list | grep mysql mysql@5.6  # 私のはver.5.6という事ですね mySQLをアンインストールして、再度インストールしてみる % brew uninstall mysql Error: No available formula or cask with the name "mysql". できませんね… # brewをclean upする % brew cleanup Removing: /usr/local/Cellar/glib/2.66.7... (441 files, 20.8MB) Warning: Skipping heroku/brew/heroku: most recent version 7.53.1 not installed Removing: /Users/takahiro/Library/Caches/Homebrew/heroku--7.52.0.tar.xz... (7.2MB) Removing: /usr/local/Cellar/python@3.9/3.9.2_1... (3,942 files, 66MB) Warning: Skipping ruby-build: most recent version 20210510 not installed Removing: /Users/takahiro/Library/Caches/Homebrew/ruby-build--20210423... (54.6KB) Pruned 2 symbolic links and 12 directories from /usr/local なんだか良い影響をもたらしたような気がしません 解決していく では、brew doctorのおっしゃる通り Some installed formulae are deprecated or disabled. You should find replacements for the following formulae: ilmbase mysql@5.6 「下のやつが非推奨か無効になってるから、代わりのもの持ってこいよ」 という意味ですね ここを対処しましょう # mysql@5.6をもう一回インストールする % brew install mysql56 Updating Homebrew... ==> Auto-updated Homebrew! Updated 1 tap (homebrew/core). ==> Updated Formulae Updated 4 formulae. うまく通りました。 インストールというより、アップデートですね # このmysql@5.6を起動してみる % brew services start mysql@5.6 Service `mysql@5.6` already started, use `brew services restart mysql@5.6` to restart. ん?もう起動されてる? 一応再起動しておきます % brew services restart mysql@5.6 Stopping `mysql@5.6`... (might take a while) ==> Successfully stopped `mysql@5.6` (label: homebrew.mxcl.mysql@5.6) ==> Successfully started `mysql@5.6` (label: homebrew.mxcl.mysql@5.6) 動いてる!! % sudo mysql.server start Starting MySQL . SUCCESS! 動いてる!! というわけで、解決いたしました。 ネットには、 - sockを自分で生成する - pidを自分で生成する という解決方法が多数出てきますが、これでも不具合は起きてしまう事があるそうです 私は再インストールで治りました でも皆さんは違うかもしれません 皆様も ネットの記事をそのまま実行せず 状況把握もしっかりと行いましょうね
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Docker ComposeでNginx+PHP+MySQL+Redis環境を構築

Docker ComposeでNginx+PHP+MySQL+Redis環境を構築 2021年現在最新のNginx+PHP+MySQL+Redis環境を構築しました 各サービス項目の説明まで Docker構成 コンテナ ミドルウェア Web Nginx PHP PHP8 DB MySQL Redis Redis ディレクトリ構成 docker_lamp/ |-- mysql | |-- dump | | `-- setup.sql | |-- logs | |-- mount | `-- settings | `-- my.cnf |-- php | |-- logs | |-- settings | | |-- php.dev.ini | | |-- php.prod.ini | | |-- www.dev.conf | | `-- www.prod.conf | `-- Dockerfile |-- project | `-- html | `-- public | `-- index.php |-- redis | `-- mount |-- web | |-- logs | `-- settings | |-- default.conf | `-- nginx.conf `-- docker-compose.yml docker-compose.yaml PHPはDockerfileを使って自分でイメージを作成 他は公式イメージを利用 一旦全体 version: '3' services: web: image: nginx:alpine volumes: - "./web/settings/default.conf:/etc/nginx/conf.d/default.conf" - "./web/settings/nginx.conf:/etc/nginx/nginx.conf" - "./project/html:/var/www/html" - "./web/logs:/var/log/nginx" ports: - "8080:80" restart: always depends_on: - php - mysql - redis php: build: ./php volumes: - "./project/html:/var/www/html" restart: always mysql: image: mysql:8.0 ports: - "13306:3306" environment: MYSQL_ROOT_PASSWORD: p@ssw0rd MYSQL_DATABASE: test MYSQL_USER: dev MYSQL_PASSWORD: dev TZ: Asia/Tokyo volumes: - "./mysql/mount:/var/lib/mysql" - "./mysql/settings/my.cnf:/etc/mysql/conf.d/my.cnf" - "./mysql/dump/setup.sql:/docker-entrypoint-initdb.d/dump.sql" - "./mysql/logs:/var/log/mysql" restart: always redis: image: redis:alpine ports: - "16379:6379" volumes: - "./redis/mount:/data" 各項目説明 Nginx 外部アクセス用に8080ポートを公開 設定ファイル、プロジェクト、ログはvolumesで同期 ※ 設定ファイルは後半に紹介 web: image: nginx:alpine volumes: - "./web/settings/default.conf:/etc/nginx/conf.d/default.conf" - "./web/settings/nginx.conf:/etc/nginx/nginx.conf" - "./project/html:/var/www/html" - "./web/logs:/var/log/nginx" ports: - "8080:80" restart: always depends_on: - php - mysql - redis PHP プロジェクトはvolumesで同期 php: build: ./php volumes: - "./project/html:/var/www/html" Dockerfile PHP用イメージ Redis、MySQLを利用するためdocker-php-ext-installを使いPHP拡張をインストール 設定ファイルをCOPYを使い反映 ※ 設定ファイルは後半に紹介 FROM php:8.0-fpm RUN apt-get update && apt-get install -y git RUN git clone https://github.com/phpredis/phpredis.git /usr/src/php/ext/redis RUN docker-php-ext-install mysqli redis COPY settings/php.dev.ini /usr/local/etc/php/conf.d/php.ini COPY settings/www.dev.conf /usr/local/etc/php-fpm.d/www.conf MySQL 外部アクセス用に13306ポートを公開 environmentの設定を行うとコンテナ作成時に自動でパスワード作成、データベース作成などが自動で実行(今回はルートパスワード設定、データベース、ユーザー、タイムゾーンを設定) リソースはvolumesを使いmount以下に同期(Dockerを停止してもデータを残す) 設定ファイル、ログはvolumesで同期 作成時に実行させたいSQLはvolumesで /docker-entrypoint-initdb.d/dump.sql に同期すると自動で実行 mysql: image: mysql:8.0 ports: - "13306:3306" environment: MYSQL_ROOT_PASSWORD: p@ssw0rd MYSQL_DATABASE: test MYSQL_USER: dev MYSQL_PASSWORD: dev TZ: Asia/Tokyo volumes: - "./mysql/mount:/var/lib/mysql" - "./mysql/settings/my.cnf:/etc/mysql/conf.d/my.cnf" - "./mysql/dump/setup.sql:/docker-entrypoint-initdb.d/dump.sql" - "./mysql/logs:/var/log/mysql" restart: always Redis 外部アクセス用に16379ポートを公開 リソースはvolumesを使いmount以下に同期(Dockerを停止してもデータを残す) redis: image: redis:alpine ports: - "16379:6379" volumes: - "./redis/mount:/data" 設定ファイル デフォルトで動かしてもいいですが、ECS運用も考慮して設定ファイルを用意 Nginx default.conf ※ 構築時にCodeigniter, FuelPHP環境の構築を考えていたのでこの形になった ポイントは fastcgi_pass php:9000; ホストをdocker-composeのサービス名(php)に変更 server { listen 80 default; server_name localhost; charset utf-8; root /var/www/html/public; index index.php index.html index.htm; location / { index index.php index.html index.htm; try_files $uri $uri/ /index.php$is_args$args; } location /admin { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; index index.php index.html index.htm; try_files $uri $uri/ /index.php$is_args$args; } location /reploxy { internal; resolver 8.8.8.8; set $reproxy $upstream_http_x_reproxy_url; proxy_pass $reproxy; proxy_set_header Authorization ""; } location ~ \.php$ { fastcgi_pass php:9000; fastcgi_index index.php; fastcgi_param FUEL_ENV "development"; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; include fastcgi_params; } } nginx.conf ログの場所など指定 user nginx nginx; worker_processes 2; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; 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 /var/log/nginx/access.log main; error_log /var/log/nginx/error.log warn; sendfile off; tcp_nopush on; tcp_nodelay off; keepalive_timeout 30; send_timeout 60; gzip on; gzip_http_version 1.0; gzip_comp_level 6; gzip_proxied any; gzip_min_length 10000; gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript; gzip_disable "MSIE [1-6] \."; include /etc/nginx/conf.d/*.conf; } PHP php.ini、www.conf設定ファイルは以下サイトを参考にさせていただきました MySQL my.cnf 文字コード、ログの場所など指定 [mysqld] # 文字コード/照合順序の設定 character-set-server = utf8mb4 collation-server = utf8mb4_bin # タイムゾーンの設定 default-time-zone = SYSTEM log_timestamps = SYSTEM # デフォルト認証プラグインの設定 default-authentication-plugin = mysql_native_password # エラーログの設定 log-error = /var/log/mysql/mysql-error.log # スロークエリログの設定 slow_query_log = 1 slow_query_log_file = /var/log/mysql/mysql-slow.log long_query_time = 5.0 log_queries_not_using_indexes = 0 # 実行ログの設定 general_log = 1 general_log_file = /var/log/mysql/mysql-query.log [mysql] default-character-set = utf8mb4 [client] default-character-set = utf8mb4 実行ファイル PHP index.php サンプルでMySQLとRedisを使う ポイントは接続ホストにDockerのサービス名を使うmysql redis <?php // MySQLテスト echo "MySQLテスト<br />"; $mysqli = mysqli_connect("mysql", "dev", "dev", "test"); $query = "SELECT * FROM `user`"; $result = $mysqli->query($query); $rows = array(); while ($row = $result->fetch_assoc()) { $rows[] = $row; } var_dump($rows); echo "<hr />"; // Redisテスト echo "Redisテスト<br />"; $redis = new Redis(); $redis->connect("redis", 6379); $redis->set('key', 'value'); echo $redis->get('key'); MySQL setup.sql サンプル用のSQL "./mysql/dump/setup.sql:/docker-entrypoint-initdb.d/dump.sql" の設定でコンテナ作成時にクエリ実行 use test; DROP TABLE IF EXISTS `test`; CREATE TABLE `user` ( `name` VARCHAR(255) NOT NULL COMMENT 'Name', `age` INT(10) unsigned NOT NULL COMMENT 'Age', `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='テスト用'; INSERT INTO `user` VALUES ("TAKASHI", 34, "0000-01-01", "9999-12-31"); docker-compose 実行 ビルドして実行 $ docker-compose up --build 確認 http://127.0.0.1:8080/ にアクセス、表示を確認 次回はこの環境下にComposer、Xdebug、PHPフレームワーク(Codeigniter予定)、UnitTest等を使えるようしていきます。 いいね!と思ったら フォロー、LGTM お願いします 【PR】プログラミング新聞リリースしました! → https://pronichi.com 【PR】週末ハッカソンというイベントやってます! → https://weekend-hackathon.toyscreation.jp/about/
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む