美文网首页
building an app the docker way

building an app the docker way

作者: 修夏起泡 | 来源:发表于2018-09-29 14:21 被阅读0次

    Dockerfile
    Defines what goes on in the environment inside your container. Access to resources like networking interfaces and disk drives is virtualized inside this environment, which is isolated from the rest of your system, so you need to map ports to the outside world, and be specific about what files you want to "copy in" to that environment.

    1. Create an empty directory, and create a file named Dockerfile. Filled the file with contents below:
      I have made a new directory named app by use mkdir app and touch dockerfile to create a file. Then vi dockerfile
     # Choose a parent image
    FROM python:2.7-slim
    
    # Set the working directory of your own
    WORKDIR /app
    
    # Copy the current directory contents into the container at /app
    COPY  . /app
    
    # Install any needed packages specified in requirements.txt
    RUN pip install --trusted-host pypi.python.org -r requirements.txt
    
    # Make port 80 available to the world outside this container
    EXPOSE 80
    
    # Define environment variable
    ENV NAME World
    
    # Run app.py when the container launched
    CMD ["python", "app.py"]
    
    1. Create requirements.txt and app.py, and keep them in the same folder with the Dockerfile

    requirements.txt

    Flask
    Redis
    

    app.py

    from flask import Flask
    from redis import Redis, RedisError
    import os
    import socket
    
    # Connect to Redis
    redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)
    
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        try:
            visits = redis.incr("counter")
        except RedisError:
            visits = "<i>cannot connect to Redis, counter disabled</i>"
    
        html = "<h3>Hello {name}!</h3>" \
               "<b>Hostname:</b> {hostname}<br/>" \
               "<b>Visits:</b> {visits}"
        return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)
    
    if __name__ == "__main__":
        app.run(host='0.0.0.0', port=80)
    
    1. Build the app
    docker build -t friendlyhello
    

    Make sure you are in the top level of your app directory. This command creates a Docker image, tagged with name friendlyhello
    To see the local Docker image registry, use

    docker image ls
    
    1. Run the app
    docker run -p 4000:80 friendlyhello
    

    If you want to run app in the background use

    docker run -d -p 4000:80 friendlyhello
    

    visit your app

    curl http://localhost:4000
    
    1. Stop the process
    # to see container id
    docker container ls
    # stop running
    docker container stop CONTAINER ID
    

    相关文章

      网友评论

          本文标题:building an app the docker way

          本文链接:https://www.haomeiwen.com/subject/grmvoftx.html