Skip to content

Commit

Permalink
Контейнеризация. Fix #871
Browse files Browse the repository at this point in the history
  • Loading branch information
Coma Grayce committed Dec 2, 2020
1 parent 848395d commit c6fce3d
Show file tree
Hide file tree
Showing 11 changed files with 354 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .dockerignore
@@ -0,0 +1,8 @@
.git*
.idea
.dockerignore
target
docker/Dockerfile
docker/docker-compose*
docker/setup-db.sh
docker/db/
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -7,3 +7,4 @@ target
*.iws
.idea
.DS_Store
docker/db/
25 changes: 25 additions & 0 deletions docker/Dockerfile
@@ -0,0 +1,25 @@
# Не собирается с помощью maven:3.6-jdk-8-slim, поэтому используем 11.
FROM maven:3.6-jdk-11-slim as builder

RUN apt-get update && apt-get upgrade -y

RUN adduser --system --shell /bin/false --home /opt/lorsource lorsource
USER lorsource
WORKDIR /opt/lorsource

# Кэшируем зависимости Maven.
COPY pom.xml .
RUN mvn dependency:resolve dependency:resolve-plugins \
&& rm pom.xml

COPY . .
COPY docker/config.properties src/main/webapp/WEB-INF/config.properties
COPY docker/liquibase.config sql/liquibase.config
RUN mvn package

COPY docker/docker-entrypoint.sh /opt/docker-entrypoint.sh
ENTRYPOINT ["/opt/docker-entrypoint.sh"]

FROM tomcat:8.5-jdk11-openjdk-slim

COPY --from=builder /opt/lorsource/target/lor-1.0-SNAPSHOT /usr/local/tomcat/webapps/ROOT
28 changes: 28 additions & 0 deletions docker/README.md
@@ -0,0 +1,28 @@
# Разработка с помощью контейнера

## Зависимости
- [Docker](https://www.docker.com/) (или [Podman](https://podman.io/) — не протестировано)
- [docker-compose](https://docs.docker.com/compose/) (или [podman-compose](https://github.com/containers/podman-compose) — не протестировано)

## Шаги
Среда разработки состоит из трёх контейнеров: development-версии, production-версии и базы данных. Для функционирования
production-версии требуется сборка development-версии, с помощью которой производятся миграции базы данных и откуда копируется
собранный движок. Оба контейнера используют одну и ту же базу данных с тестовыми данными.

### Development-версия с Jetty
- Склонируйте репозиторий и перейдите в директорию `docker/`.
- Соберите движок. `docker-compose -f docker-compose.dev.yml build web`
- Запустите базу данных. `docker-compose -f docker-compose.dev.yml up -d db`
- Запустите скрипт с остальными действиями над базой данных. `docker-compose -f docker-compose.dev.yml exec db /opt/setup_db.sh`
- Запустите движок. `docker-compose -f docker-compose.dev.yml up web`

Миграции базы данных будут совершены автоматически. Сервер будет доступен по адресу `http://localhost:8080`.

### Production-версия с Tomcat
Напоминаем, что для работы этого контейнера вам нужен собранная development-версия и база данных с уже совершёнными миграциями.

- Остановите работающий development-контейнер.
- Соберите движок. `docker-compose build web`
- Запустите движок. `docker-compose up web`

Сервер будет доступен по адресу `http://localhost:8080`.
55 changes: 55 additions & 0 deletions docker/config.properties
@@ -0,0 +1,55 @@
#
# Copyright 1998-2016 Linux.org.ru
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

MainUrl=http://127.0.0.1:8080/
SecureUrl=http://127.0.0.1:8080/
WSUrl=ws://127.0.0.1:8080/
activemq.path=target/tmp/activemq
HTMLPathPrefix=target/lor-1.0-SNAPSHOT/
upload.path=target/uploads/
Secret=secret
# development keys - for use on localhost only
recaptcha.private=6LcdM0oUAAAAANYhnHF3jmD1r1TvkiyPaWHjC83x
recaptcha.public=6LcdM0oUAAAAAD2T-0ZW2HPkqZ5nFi1Y52U7BOMI

EnableHsts=false
# admin.emailAddress=bugz@linux.org.ru
admin.emailAddress=specify_your_real_email_if_you_want_receive_messages

# разрешение модераторам на редактирование комментов пользователей
comment.isModeratorAllowedToEdit=false

# время (в минутах), в течении которого с момента создания коммента его
# можно редактировать (не распространяется на модераторов).
# если не установлено или равно 0, то редактировать можно будет всегда.
comment.expireMinutesForEdit=30

# разрешить редактировать комментарии, которые имеют ответы
comment.isEditingAllowedIfAnswersExists=false

# сколько скора должно быть у пользователя, чтобы он смог
# редактировать комментарии если не установлено,
# то редактировать могут все. Если установлено огромное
# число, то комментарии будут фактически отключены
comment.scoreValueForEditing=45

# "embedded" или host:port
Elasticsearch=embedded

jdbc.url=jdbc:postgresql://db:5432/lor?stringtype=unspecified
#jdbc.url=jdbc:postgresql://127.0.0.1:5432/real-lor?stringtype=unspecified
jdbc.user=linuxweb
jdbc.password=linuxweb
jdbc.poolSize=10
25 changes: 25 additions & 0 deletions docker/docker-compose.dev.yml
@@ -0,0 +1,25 @@
version: "3.4"

services:
web:
build:
context: ../
dockerfile: docker/Dockerfile
target: builder
restart: always
ports:
- 8080:8080
depends_on:
- db

db:
image: postgres:11-alpine
restart: always
volumes:
- ./db:/var/lib/postgresql/data:z
- ./setup_db.sh:/opt/setup_db.sh:z
- ../sql/demo.db:/opt/demo.db:z
environment:
- POSTGRES_DB=lor
- POSTGRES_USER=maxcom
- POSTGRES_PASSWORD=maxcom
26 changes: 26 additions & 0 deletions docker/docker-compose.yml
@@ -0,0 +1,26 @@
version: "3"

services:
web:
build:
context: ../
dockerfile: docker/Dockerfile
restart: always
ports:
- 8080:8080
volumes:
- ./server.xml:/usr/local/tomcat/conf/server.xml:z
depends_on:
- db

db:
image: postgres:11-alpine
restart: always
volumes:
- ./db:/var/lib/postgresql/data:z
- ./setup_db.sh:/opt/setup_db.sh:z
- ../sql/demo.db:/opt/demo.db:z
environment:
- POSTGRES_DB=lor
- POSTGRES_USER=maxcom
- POSTGRES_PASSWORD=maxcom
3 changes: 3 additions & 0 deletions docker/docker-entrypoint.sh
@@ -0,0 +1,3 @@
#!/bin/sh
mvn liquibase:update -Dliquibase.promptOnNonLocalDatabase=false
mvn jetty:run
6 changes: 6 additions & 0 deletions docker/liquibase.config
@@ -0,0 +1,6 @@
driver: org.postgresql.Driver
contexts: production
url: jdbc:postgresql://db:5432/lor
username: maxcom
password: maxcom
changeLogFile: sql/main.xml
172 changes: 172 additions & 0 deletions docker/server.xml
@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener" />
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>

<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">

<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->


<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the
AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the APR/native implementation which always uses
OpenSSL for TLS.
Either JSSE or OpenSSL style configuration may be used. OpenSSL style
configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
-->

<!-- Define an AJP 1.3 Connector on port 8009 -->
<!--
<Connector protocol="AJP/1.3"
address="::1"
port="8009"
redirectPort="8443" />
-->

<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->

<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">

<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->

<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>

<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">

<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->

<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>
</Engine>
</Service>
</Server>
5 changes: 5 additions & 0 deletions docker/setup_db.sh
@@ -0,0 +1,5 @@
#!/bin/sh
createuser -U maxcom linuxweb
createuser -U maxcom jamwiki
psql -U maxcom -c "ALTER USER linuxweb PASSWORD 'linuxweb'" template1
psql -U maxcom -f /opt/demo.db lor

0 comments on commit c6fce3d

Please sign in to comment.