Add docker

This commit is contained in:
linmeideli committed 2026-11-06 12:17:07 +08:00
1 parent fe74042513
commit bd1d0d32b5
5 files changed
+229 -1

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
.git
.github
.idea
.vs
.vscode
**/bin
**/obj
build
/Data
/Log
/Update
/updates
**/__pycache__
*.user
*.suo
*.log
Dockerfile*
compose*.yml
docker-compose*.yml
.dockerignore
/config.json
/plugins
/libraries
+40
View File
@@ -0,0 +1,40 @@
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG TARGETARCH
ARG VERSION_SUFFIX=docker
WORKDIR /source
COPY src/ ./src/
RUN case "$TARGETARCH" in \
amd64) RID=linux-x64 ;; \
arm64) RID=linux-arm64 ;; \
arm) RID=linux-arm ;; \
*) echo "Unsupported target architecture: $TARGETARCH" >&2; exit 1 ;; \
esac && \
dotnet restore -r "$RID" ./src/Empostor.Server/Empostor.Server.csproj && \
dotnet publish ./src/Empostor.Server/Empostor.Server.csproj \
--configuration Release \
--runtime "$RID" \
--no-restore \
--self-contained false \
-p:PublishSingleFile=true \
-p:PublishTrimmed=false \
-p:VersionSuffix="$VERSION_SUFFIX" \
--output /app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app/ ./
COPY marketplace/ ./marketplace/
RUN mkdir -p Data Log Pages Languages languages plugins libraries Update \
&& chown -R app:app Data Log Pages Languages languages plugins libraries Update \
&& chmod 0750 Data Log Pages Languages languages plugins libraries Update
ENV DOTNET_RUNNING_IN_CONTAINER=1
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1
USER app
ENTRYPOINT ["./Empostor.Server"]
+24 -1
View File
@@ -26,7 +26,30 @@ Download the build you'd like from the [releases](https://github.com/Empostor/Em
Unzip the file and go to config.json. To make your server playable for other devices, replace the "PublicIp" field with your actual public IP address.
It is also recommended to [set up a Reverse Proxy](https://empostor.github.io/get-started/reverse-proxy#use-a-reverse-proxy) (for HTTPS connections).
It is also recommended to [set up a Reverse Proxy](https://empostor.github.io/get-started/reverse-proxy#use-a-reverse-proxy) (for HTTPS connections).
### Docker
Docker Compose port mappings are generated from `config.json` before the container starts. Install Docker Engine with Compose v2 and Python 3.9 or newer. Copy `src/Empostor.Server/config.json` to `config.json` in the repository root and set `Server.PublicIp` to your public IP or domain, then run:
```sh
python3 docker-up.py
```
On Windows, use `python docker-up.py`. If `config.json` is missing, the script creates it from the repository defaults. The script builds the image and starts the service. Set `EMPOSTOR_CONFIG` to use a different configuration file; the launcher reads and mounts that same file read-only.
| Configuration | Published ports |
| --- | --- |
| HTTP enabled | `HttpServer.ListenPort/tcp`, with the same host and container port |
| DeltaPort range enabled | `DeltaPortStart` through `DeltaPortEnd/udp`, with identical host and container ranges |
| GameCode with `GameCodePorts` | Only `GameCodePorts[0]/udp` |
| GameCode with an empty list, or DeltaPort range disabled | `PublicPort:ListenPort/udp` |
After changing port or verification settings, rerun `python3 docker-up.py up -d --force-recreate` to regenerate the mappings and reload the configuration. Use the launcher for other Compose commands too, for example `python3 docker-up.py logs -f` or `python3 docker-up.py down`. Running `docker compose up` directly does not generate port mappings.
Keep `Server.ListenIp` and `HttpServer.ListenIp` at `0.0.0.0` for IPv4 bridge networking. Keep `UseUfw` and `UseFirewalld` disabled inside the container and allow the published ports in the host/cloud firewall. The default DeltaPort range publishes 20,001 UDP ports, which can be slow to create in Docker; reduce the range to suit your expected player count, or use GameCode for a single shared UDP port. The pool also reserves `DeltaPortLowWaterMark` ports (default 5).
The image runs as the non-root `app` user. Persistent Docker volumes hold `Data`, `Log`, `plugins`, `libraries`, `Pages`, `Languages`, `languages`, and `Update`; plugin files and generated configurations in these directories remain writable across container recreation. Program files and the bundled `marketplace` catalog/assets remain root-owned. Empty named volumes receive the image's initial contents, including bundled pages/themes. Existing volumes retain their contents when the image is rebuilt; back them up and update bundled assets separately when needed. Installed plugins can be managed through the admin marketplace. For host bind mounts instead of named volumes, grant the container user write access (UID 1654 in the .NET 8 image). Custom plugin output paths must point into a writable mounted directory.
## Client Setup
+35
View File
@@ -0,0 +1,35 @@
services:
empostor:
build:
context: .
dockerfile: Dockerfile
image: empostor-server:local
container_name: empostor-server
restart: unless-stopped
init: true
ports: []
volumes:
- type: bind
source: ${EMPOSTOR_DOCKER_CONFIG:-./config.json}
target: /app/config.json
read_only: true
bind:
create_host_path: false
- empostor-data:/app/Data
- empostor-log:/app/Log
- empostor-pages:/app/Pages
- empostor-languages:/app/Languages
- empostor-languages-lower:/app/languages
- empostor-plugins:/app/plugins
- empostor-libraries:/app/libraries
- empostor-updates:/app/Update
volumes:
empostor-data:
empostor-log:
empostor-pages:
empostor-languages:
empostor-languages-lower:
empostor-plugins:
empostor-libraries:
empostor-updates:
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Generate Docker Compose port mappings from Empostor config.json and start it."""
import json
import os
import pathlib
import subprocess
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent
CONFIG = pathlib.Path(os.environ.get("EMPOSTOR_CONFIG", ROOT / "config.json")).resolve()
COMPOSE = ROOT / "compose.yml"
def port(value, label):
if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 65535:
raise ValueError(f"{label} must be an integer from 1 to 65535")
return value
def delta_port(value, label):
if isinstance(value, int) and not isinstance(value, bool) and value == 0:
return 0
return port(value, label)
def port_mappings(config):
if not isinstance(config, dict):
raise ValueError("config.json must contain a JSON object")
config = {key.lower(): value for key, value in config.items()}
server = config.get("server", {})
http = config.get("httpserver", {})
if not isinstance(server, dict) or not isinstance(http, dict):
raise ValueError("Server and HttpServer config entries must be JSON objects")
server = {key.lower(): value for key, value in server.items()}
http = {key.lower(): value for key, value in http.items()}
mappings = set()
http_enabled = http.get("enabled", True)
if not isinstance(http_enabled, bool):
raise ValueError("HttpServer.Enabled must be a JSON boolean")
if http_enabled:
http_port = port(http.get("listenport", 22023), "HttpServer.ListenPort")
mappings.add(f"{http_port}:{http_port}/tcp")
listen_port = port(server.get("listenport", 22023), "Server.ListenPort")
public_port = port(server.get("publicport", 22023), "Server.PublicPort")
mode = str(server.get("verificationmode", "DeltaPort")).lower()
if mode in ("gamecode", "1"):
game_ports = server.get("gamecodeports", [])
if not isinstance(game_ports, list):
raise ValueError("Server.GameCodePorts must be an array")
internal_port = port(game_ports[0], "Server.GameCodePorts[0]") if game_ports else listen_port
external_port = internal_port if game_ports else public_port
mappings.add(f"{external_port}:{internal_port}/udp")
elif mode in ("deltaport", "0"):
start = delta_port(server.get("deltaportstart", 0), "Server.DeltaPortStart")
end = delta_port(server.get("deltaportend", 0), "Server.DeltaPortEnd")
if start > 0 and end >= start:
mappings.add(f"{start}-{end}:{start}-{end}/udp")
else:
mappings.add(f"{public_port}:{listen_port}/udp")
else:
raise ValueError("Server.VerificationMode must be DeltaPort or GameCode")
return sorted(mappings)
def main():
if not CONFIG.is_file():
default_config = ROOT / "src" / "Empostor.Server" / "config.json"
CONFIG.parent.mkdir(parents=True, exist_ok=True)
CONFIG.write_bytes(default_config.read_bytes())
print(f"Created {CONFIG} from the repository default config.")
with CONFIG.open(encoding="utf-8-sig") as stream:
config = json.load(stream)
mappings = port_mappings(config)
override = "services:\n empostor:\n ports:\n"
override += "".join(f' - "{item}"\n' for item in mappings)
with tempfile.NamedTemporaryFile("w", encoding="utf-8", suffix=".yml", delete=False) as stream:
stream.write(override)
override_path = pathlib.Path(stream.name)
try:
command = ["docker", "compose", "-f", str(COMPOSE), "-f", str(override_path)]
command.extend(sys.argv[1:] or ["up", "-d", "--build"])
environment = dict(os.environ, EMPOSTOR_DOCKER_CONFIG=str(CONFIG))
print("Publishing:")
for item in mappings:
print(f" {item}")
raise SystemExit(subprocess.call(command, cwd=ROOT, env=environment))
finally:
override_path.unlink(missing_ok=True)
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, json.JSONDecodeError) as error:
print(f"docker-up: {error}", file=sys.stderr)
raise SystemExit(2)