# SonarQubeをDockerで立ててコード解析をしてみる
## SonarQubeの公式イメージを取ってきてコンテナ立てる
```
$ docker run -itd --name sonar -p 9001:9000 sonarqube:lts
```
SonarQubeのポートは9000なので、ポートフォワーディングで9001ポートから9000ポートに繋ぐ。
## ブラウザからSonarQubeにログインする
`http://localhost:9091`にアクセスしてログインする。
初回は、`User: admin, Pass: admin`。
## SonarQubeプロジェクトを作成する
Project KeyやDisplay Nameを設定する。
Sonar-ScannerがSonarQubeを使用するためのアクセストークンを作成する。
## Sonarコンテナにログインし、Sonar-Scannerをダウンロードする
Sonarコンテナにunzipコマンドを入れ、ダウンロードしたSonar-Scannerを展開する。
```
$ docker exec -it -u root sonar bash
root@edcb2a00a140:/opt/sonarqube# pwd
/opt/sonarqube
root@edcb2a00a140:/opt/sonarqube# unzip sonar-scanner-cli-5.0.1.3006-macosx.zip
root@edcb2a00a140:/opt/sonarqube# ll
total 90104
dr-xr-xr-x 1 root root 4096 Oct 3 13:47 ./
drwxr-xr-x 1 root root 4096 Oct 3 13:21 ../
dr-xr-xr-x 2 root root 4096 Sep 6 00:12 bin/
dr-xr-xr-x 2 root root 4096 Sep 5 07:34 conf/
-r-xr-xr-x 1 root root 7651 Sep 5 07:34 COPYING*
drwxrwxrwx 1 root root 4096 Oct 3 02:20 data/
-r-xr-xr-x 1 root root 77558 Sep 5 07:36 dependency-license.json*
drwxr-xr-x 2 root root 4096 Sep 6 00:13 docker/
dr-xr-xr-x 7 root root 4096 Sep 5 07:41 elasticsearch/
drwxrwxrwx 1 root root 4096 Oct 3 02:20 extensions/
dr-xr-xr-x 5 root root 4096 Sep 6 00:12 lib/
drwxrwxrwx 1 root root 4096 Oct 3 02:20 logs/
drwxr-xr-x 6 root root 4096 Aug 4 19:32 sonar-scanner-5.0.1.3006-macosx/
-rw-r--r-- 1 root root 44986663 Aug 4 19:44 sonar-scanner-cli-5.0.1.3006-macosx.zip
drwxrwxrwx 1 root root 4096 Oct 3 02:20 temp/
dr-xr-xr-x 5 root root 4096 Sep 5 07:42 web/
root@edcb2a00a140:/opt/sonarqube#
```
`sonar-scanner`コマンドが使えるようにパスを通す。
## Sonarコンテナにソースコードを配置する
適当なアプリケーションを作成し、Sonarコンテナ上にコピーする。
```
$ npx create-react-app sample-react-app --template typescript
$ docker cp sample-react-app sonar:/opt
Successfully copied 277MB to sonar:/opt
$ docker exec -it -u root sonar bash
root@edcb2a00a140:/opt# ls -l
total 16
drwxr-xr-x 1 root root 4096 Sep 1 23:30 java
drwxr-xr-x 6 501 dialout 4096 Oct 3 13:13 sample-react-app
dr-xr-xr-x 1 root root 4096 Oct 3 12:48 sonarqube
```
## ソースコードを解析する
**下記の通り、コマンド実行は失敗。
原因はマシンがApple Siliconのためだと思われるので原因調査を行なう。**
SonarQubeのImageがarm64じゃないかも。。
```
root@edcb2a00a140:/opt/sample-react-app# sonar-scanner \
-Dsonar.projectKey=sample-project \
-Dsonar.sources=. \
-Dsonar.host.url=http://localhost:9091 \
-Dsonar.login=${token}
qemu-x86_64: Could not open '/lib64/ld-linux-x86-64.so.2': No such file or directory
root@edcb2a00a140:/opt/sample-react-app#
```
## ちなみにQuality Gateの設定
デフォルト設定は以下。
