# Docker Deployment

# Introduction

For a long time, the environment has always been a difficult problem for deployment. If there are conflicting configurations in your project, you have to spend a lot of time resolving them. Fortunately, virtualization provides us with a good solution. Docker is one of them. If you don't know Docker, you can visit Docker official website (opens new window) to learn more.

# Build Image

Let's start with a simple project. We will use a Sanic project as an example. Assume the project path is /path/to/SanicDocker.

The directory structure looks like this:

# /path/to/SanicDocker
├── requirements.txt
├── dockerfile
└── server.py

And the server.py code looks like this:

app = Sanic("MySanicApp")
async def hello(request):
    return text("OK!")
if __name__ == '__main__':
    app.run(host='', port=8000)


Please note that the host cannot be . In docker container, is the default network interface of the container, only the container can communicate with other containers. more information please visit Docker network (opens new window)

Code is ready, let's write the Dockerfile:

FROM sanicframework/sanic:3.8-latest
WORKDIR /sanic
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "server.py"]

Run the following command to build the image:

docker build -t my-sanic-image .

# Start Container

After the image built, we can start the container use my-sanic-image:

docker run --name mysanic -p 8000:8000 -d my-sanic-image

Now we can visit http://localhost:8000 to see the result:


# Use docker-compose

If your project consist of multiple services, you can use docker-compose (opens new window) to manage them.

for example, we will deploy my-sanic-image and nginx, achieve through nginx access sanic server.

First of all, we need prepare nginx configuration file. create a file named mysanic.conf:

server {
    listen 80;
    listen [::]:80;
    location / {
      proxy_pass http://mysanic:8000/;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection upgrade;
      proxy_set_header Accept-Encoding gzip;

Then, we need to prepare docker-compose.yml file. The content follows:

version: "3"
    image: my-sanic-image
      - "8000:8000"
    restart: always
    image: nginx:1.13.6-alpine
      - "80:80"
      - mysanic
      - ./mysanic.conf:/etc/nginx/conf.d/mysanic.conf
    restart: always
    driver: bridge

After that, we can start them:

docker-compose up -d

Now, we can visit http://localhost:80 to see the result:

MIT Licensed
Copyright © 2018-present Sanic Community Organization

~ Made with ❤️ and ☕️ ~