How to write docker yaml file
To write a Docker YAML file, you will need to create a Docker Compose file which is a YAML file used to define and run multi-container Docker applications.

Here's a basic example of a Docker Compose file:

```yaml
version: '3.9'
services:
  web:
    build: .
    ports:
      - 5000:5000
  redis:
    image: redis:alpine
```

In this example, there are two services: `web` and `redis`. The `web` service is built from the current directory (`.`) and exposes port 5000 on the host. The `redis` service uses the Redis Alpine image.

Here's an explanation of the key components in this file:

- `version`: specifies the version of the Docker Compose file format to use.
- `services`: a list of services that make up your application.
- `build`: specifies the path to the Dockerfile to use to build the container.
- `image`: specifies the name of the image to use for the container.
- `ports`: specifies the ports to expose on the host machine.

You can add additional configuration options to each service as needed, such as environment variables, volumes, and more. Once you've created your Docker Compose file, you can use the `docker-compose` command to start and stop your application.
Optimize the code
The code provided is a YAML file and is already quite optimized. However, here are a few suggestions to make the code even more efficient:

1. Use the latest version of Docker Compose if possible to take advantage of the latest features and improvements.
2. Use the shorthand notation for port mapping to make the code more concise. For example, 5000:5000 can be written as 5000.
3. Avoid using unnecessary quotes around values unless they contain special characters. For example, redis:alpine can be written as redis:alpine.
4. Use caching when building containers to speed up the build process. This can be done by adding a cache_from parameter to the build section.
Here is an optimized version of the code with these suggestions applied:

```
version: '3.9'
services:
web:
build: .
ports:
- 5000
redis:
image: redis:alpine
cache_from:
- redis:alpine
```